最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Removing field value after User changes the value of a related field (RAILS) - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Jan 20 at 16:46 Kelvin TanjuecoKelvin Tanjueco 51 bronze badge 1
  • Rubocop is your friend here. – max Commented Jan 21 at 11:32
Add a comment  | 

1 Answer 1

Reset to default 2

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.

发布评论

评论列表(0)

  1. 暂无评论