Rails 3 check if attribute changed

前端 未结 5 717
渐次进展
渐次进展 2020-11-29 17:53

Need to check if a block of attributes has changed before update in Rails 3.

street1, street2, city, state, zipcode

I know I could use something like

5条回答
  •  孤街浪徒
    2020-11-29 18:16

    ActiveModel::Dirty didn't work for me because the @model.update_attributes() hid the changes. So this is how I detected changes it in an update method in a controller:

    def update
      @model = Model.find(params[:id])
      detect_changes
    
      if @model.update_attributes(params[:model])
        do_stuff if attr_changed?
      end
    end
    
    private
    
    def detect_changes
      @changed = []
      @changed << :attr if @model.attr != params[:model][:attr]
    end
    
    def attr_changed?
      @changed.include :attr
    end
    

    If you're trying to detect a lot of attribute changes it could get messy though. Probably shouldn't do this in a controller, but meh.

提交回复
热议问题