ActiveRecord: change and save object state inside model
I have the following code:
def incoming_acceptation(incoming_code)
if invite_code == incoming_code
开发者_Go百科 accepted = true
self.save
true
else
false
end
end
But it does not change and save accepted to true, it remains in the previous state, false.
@i.incoming_acceptation(incoming_code) => true
@i.accepted => false
I recommend:
def incoming_acceptation(incoming_code)
update_attribute(:accepted, true) if invite_code == incoming_code
end
update_attribute
will change and save that attribute. There's also update_attributes
(notice the s
) that accepts Hash to change multiple attributes at once:
@obj.update_attributes(:accepted => true, :accepted_at => Time.now)
Note: update_attribute
and update_attributes
both return true
when the change and save were successful, just like in your example.
self.accepted = true
精彩评论