开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜