What is the easiest way to set all attributes (except id, created_at, updated_at) of an ActiveRecord object to nil?
There's an array called attribute_names
on the model, which does include all attributes, so use reject to filter attributes:
class Model < AR::Base
def nilify_attributes!(except = nil)
except ||= %w{id created_at updated_at}
attribute_names.reject { |attr| except.include?(attr) }.each { |attr| self[attr] = nil }
end
end
See http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-attribute_names
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With