Activerecord Attributes And Setting Foreign Keys

I have a unit test that tries to save a record in a table with three foreign keys. But somehow that test failed unless I explicitly assigned the foreign keys via the accessors.

The test below passes with two assertions




public function testSaveViaAttributesWithForeignKeys(){

	$employee = $this->emp('student1');

	$timeEntry = new TimeEntry();

	$timeEntry->attributes = array(

		'student_id' => $employee->id, 

		'date' => 1387152000, 

		'hours_worked' => 8.00, 

		'hours_type_id' => 1, 

		'status_id' => 1

	);

	try {

		$timeEntry->save();

	} catch (Exception $e) {

		$timeEntry->student_id = $employee->id;

		$timeEntry->hours_type_id = 1;

		$timeEntry->status_id = 1;

		$this->assertTrue($timeEntry->save());

		$this->assertTrue(isset($e));

	}

}



Is this a bug or should I not specify foreign keys via the attributes array?

Assigning the attributes uses the setAttributes setter, which by default, sets only safe attributes. Apparently you have some rules that makes those FKs unsafe.

Try calling setAttributes($attributes, false) or adjust your rules.

Thanks a lot that fixed it.