I am trying to automatically remove the assigned value of the column name "table_number" if the User changes the value of the column_name "status" to "no" in the RSVP Form.
I am trying to do this in the model of my rsvp.rb with the following code:
class Rsvp < ApplicationRecord
after_commit :remove_table_assignment, :if => :status_changed?
def remove_table_assignment
if self.status = "no"
self.table_number = nil
end
end
end
This doesn't do what I am trying to achieve nor it throws error.
self.status = "no"
is assignment so you are setting the status to "no"
every time and this will always evaluate to to a "truthy" value. Since this is in an after_commit
the change is not persisted unless you save again, so in essence what you are doing is.
rsvp.save
rsvp.status = "no"
rsvp.table_number = nil
I think what you are looking for is:
before_save :remove_table_assignment, :if => :status_changed?
def remove_table_assignment
if self.status.downcase == "no"
self.table_number = nil
end
end
This event will trigger occur before the record is saved so the table_number
assignment will persist, if the String equality as the conditional evaluates to true
.