Rails 3 check if attribute changed

前端 未结 5 708
渐次进展
渐次进展 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:12

    This is how I solved the problem of checking for changes in multiple attributes.

    attrs = ["street1", "street2", "city", "state", "zipcode"]
    
    if (@user.changed & attrs).any?
      then do something....
    end
    

    The changed method returns an array of the attributes changed for that object.

    Both @user.changed and attrs are arrays so I can get the intersection (see ary & other ary method). The result of the intersection is an array. By calling any? on the array, I get true if there is at least one intersection.

    Also very useful, the changed_attributes method returns a hash of the attributes with their original values and the changes returns a hash of the attributes with their original and new values (in an array).

    You can check APIDock for which versions supported these methods.

    http://apidock.com/rails/ActiveModel/Dirty

提交回复
热议问题