Question

I was trying out the self join example given in rails guide. I added a 'manager_id' field to the table.

The problem is, after associating the two objects, it is not reflected until I call 'save'.

I tested it through the console in development mode:

> boss, emp = 2.times.map { FactoryGirl.create :employee }
> emp.manager = boss
> emp.manager_id == boss.id
=> true
> boss.subordinates
=> []

If I now save 'emp', I'm getting the desired result.

> emp.save
> boss.subordinates
=> [#Employee obj]

Why is that so? Do I have to use the same approach for writing test cases too? Somehow I feel I'm doing it wrong and there should be a better way.

Was it helpful?

Solution

In your first code example, your instance of emp has been assigned a manager but your boss object does not have any subordinates and none exist in the database yet.

Until you call save on emp, ActiveRecord will not know that you added boss as a manager to another object. When you call save, the record will be saved to the database.

There is nothing wrong with saving the record to the database for your test scripts, as long as you have a cleanup script that will delete unwanted records after you create them. This will also test for your model's validation and associations.

OTHER TIPS

When you call boss.subordinates, ROR make SQL request like this:

Select * from subordinates where subordinates.id = #{id}

In your case there is no record in database for subordinates and you get nothing.

You must save record in database to make you association work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top