activerecord - Problem updating a record that has an association in Rails -


i'm not able update record has association in rails.

for example, have post model , user model. in post.rb i've included association belongs_to :user.

if want change user_id field existing post record, doesn't work.

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

the above doesn't change post record's user_id field 5. when remove association, above code works.

is there way update user_id field without removing association?

thanks!

tim

you wrote:

these examples should work reason user_id remains unchanged. maybe has validations

you can verify if it's due validations replacing "save" "save!"

the former returns false if of validations fail, whereas latter raise exception:

p = post.find(1) p.user = user.find(5) p.save! 

alternatively, can following in rails console:

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

good luck!


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -