Tim
Tim

Reputation: 1461

Problem updating a record that has an association in Rails

I'm not able to update a record that has an association in Rails.

For example, I have a Post model and a User model. In post.rb I've included the association belongs_to :user.

If I want to change the user_id field for an existing Post record, it doesn't work.

p = Post.find(1)
p.user_id = 5
p.save

The above doesn't change the Post record's user_id field to 5. When I remove the association, the above code works.

Is there a way to update the user_id field without removing the association?

Thanks!

Tim

Upvotes: 0

Views: 1393

Answers (2)

pvandenberk
pvandenberk

Reputation: 4798

You wrote:

These examples look like they should work but for some reason the user_id remains unchanged. Maybe it has something to do with the validations

You can easily verify if it's due to validations by replacing "save" with "save!"

The former just returns false if any of the validations fail, whereas the latter will raise an exception:

p = Post.find(1)
p.user = User.find(5)
p.save!

Alternatively, you can also do the following in a Rails console:

>> p = Post.find(1)
...
>> p.user = User.find(5)
...
>> p.valid?
... 
>> # will be either true or false, depending on validations
>> p.errors.full_messages
... 
>> # will be either [] or else a non-empty array of all validation failures
>> _

Good luck!

Upvotes: 1

pvandenberk
pvandenberk

Reputation: 4798

The "proper" way to do this is to let Rails do all the heavy-lifting, as follows:

p = Post.find(1)
p.user = User.find(5)
p.save

... which will work, assuming all validations are met.

Alternatively:

Post.find(1).update_attribute(:user_id, 5)

... although you probably want to think twice before using the latter! :-)

Peter

Upvotes: 1

Related Questions