This exists here for my easy access. May or may not be useful for others.

I paste this gist here, so that I have a easily accessible permalink to refer these. The awesomeness of gist helps me to keep it updated, without ever needing to touch this post again :D

Published at : Thursday May,31 2012 at 01:11 | Tags : ruby, rails, hacking, | View Comments

Today at work I was writing some rspec tests for a Model and found out the test cases failing for some mysterious reason in ActiveRecord. I tried plunging into rails source code to find out the exact point of failure., but then I burnt a whole afternoon with no good result. Thought of writing it here, so that I can try again when I have time later.

The scenario is simple.,

I have a Model named AAA which has a self referential relationship as below,

Imagine this model has only two attributes id and parent_id. Now begins the weirdness. Look at the gist below.

  • I create two objects a and b from model AAA.

  • I am assinging b's parent as a.

  • Then I delete a.

  • Now b points to a parent which is non existent. I then try to assign nil to the 'parent_id' attribute of the b.

  • And then save it!.

  • Rails doesn't complain anything. But when you try to print b again. SEE the parent_id attribute is still set to a's id.

  • No matter what you assign, this doesn't change. No errors nothing.

  • The only way to change is instead of assingning anything to parent_id, assing nil using the association directly. Like., 'b.parent = nil'

  • Now that thing works and I DONT KNOW WHY!!!

Published at : Wednesday May,30 2012 at 18:41 | Tags : ruby, rails, hacking, | View Comments
Browse Archives
I am..
Azhagu Selvan SP
Atheist, FOSS enthusiast,
Pythonist, Student
Creative Commons License