Tuesday, April 14, 2009

Rails foreign key assignment and belongs_to associations

I keep getting bitten by some odd behaviour in the way Rails handles assignment to the foreign key attribute of a belongs_to association. Specifically, assigning the foreign key id directly, as one might do when processing a form submission with mass attribute assignment, only works for new records or records where the belongs_to association has not already been loaded.

There's a long-standing ticket for this issue here, but little progress seems to have been made in resolving it.

Frankly, this is a pain in the ass. I wasted a ton of effort on trying to workaround this problem, finally resorting to monkey patching ActiveRecord, which then broke when we tried to upgrade our application to Rails 2.2.2.

On another trip on the merry-go-round this morning, I got lucky and finally spotted a solution that I'd missed before. While others were debating the merits / demerits of various patches and whether all cases were adequately covered, Matt West who opened the ticket, provided a fix in the form of a plugin:

http://code.torchbox.com/svn/rails/plugins/belongs_to_synchronisation/

Unfortunately, it was hidden in a blog post linked from the ticker. See the original blog post here.