Multiplay Labs

tech hits and tips from Multiplay

Rails belongs_to breaks attribute assignments

without comments

So belongs_to and other auto associations in rails are a great time saver, until they break and prevent attribute assignments that is 🙁

So here’s an example of the problem:-

# created_state_id = 1
# published_state_id = 2
post = "my post", "stuff..." )
post.state = created "Post saved: #{post.state_id}"
.... "Before update: #{post.state_id}"
post.state_id = published_state_id "After update: #{post.state_id}" "After save: #{post.state_id}"

You would expect that after the second save that post.state_id would be 2 yes? Well its not; the output from the above would be:
> Post saved: 1
> Before update: 1
> After update: 2
> After save: 1

So what’s the deal? The problem is that the assignment to post.state before the first call flags the association, in BelongsToAssociation, as updated but this updated flag is never cleared even after save, so after that point its impossible to change the value of state_id via direct assignment.

Quite a serious issue really as information is lost. The only way to avoid this is to only ever assign using either the association or the attribute i.e. don’t mix and match the two.

I’ve raised this as part of the bigger update issue when changing attributes that are the pk of an association so keep your eye on: Rails issue #142: belongs_to association not updated when assigning to foreign key

Written by Dilbert

July 24th, 2009 at 6:47 pm

Posted in Hackery,Rails

Leave a Reply

You must be logged in to post a comment.