Advertisement
d4rky

Untitled

Mar 31st, 2015
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 0.77 KB | None | 0 0
  1. # response to http://www.davidverhasselt.com/set-attributes-in-activerecord/#comment-1663663372
  2. # just remember that this code requires you to either use super or attr_name_will_change! in your overridden setters and getters
  3. # @see http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
  4. def update_attribute_without_other_attributes(name, value)
  5.   # get all changed values (self.changes returns hash with [ old_value, new_value ] or nil as values, we only want new_value)
  6.   changes_before = self.changes.inject({}) { |h, (k,v)| h[k] = (v.respond_to?(:last) ? v.last : v); h }
  7.   changes_before.delete name
  8.   restore_attributes # reset_changes for Rails 4.1
  9.  
  10.   save_result = update_attribute(name, value)
  11.   # restore changes
  12.   attributes(changes_before)
  13.   save_result
  14. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement