Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: change and save object state inside model

I have the following code:

  def incoming_acceptation(incoming_code)
    if invite_code == incoming_code
      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
like image 895
rtacconi Avatar asked Aug 10 '26 01:08

rtacconi


1 Answers

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.

like image 54
Ariejan Avatar answered Aug 11 '26 16:08

Ariejan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!