views:

19

answers:

2

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
+2  A: 
self.accepted = true
jordinl
I tried that an was not working... then I get confused. Anyway thanks.
rtacconi
It is worth pointing out that the reason for this is that without the `self.`, `accepted` is interpreted as a local variable within `incoming_acceptation` so the assignment does not change the attribute value.
mikej
+3  A: 

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.

Ariejan