0

I have the following function in my model

after_save :update_status

def update_status
  if quantity_received >= quantity
    self.received = true
  else
    self.received = false
  end
end

True works great but it doesn't update to false when set to true. Any idea?

2 Answers 2

2

When you're defining a callback it is very important you do not inadvertently return false, which is a signal to halt the chain, and that's what you're doing here in one case.

A re-written version that avoids this problem is:

after_save :update_status

def update_status
  self.received = quantity_received >= quantity

  return
end

You can return anything but false, so the last line could be nil or true just the same.

Sign up to request clarification or add additional context in comments.

2 Comments

In this case I might not need to store this in the Db. If I do def status quantity_received >= quantity ? true : false end How to render image_tag if true in the view?
There's no reason to do cond ? true : false because that's equivalent to cond if the condition is a boolean, or !!cond otherwise.
1

You're assigning to received "after" save. So this assignment doesnt get saved!

Try

before_save :update_received

def update_received
  self.received = quantity_received >= quantity
end

And by "saved" i assume you mean "saved" in the database.

1 Comment

Thanks for your reply. The 2 solutions combined just work fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.