What is the easiest way to set all attributes (except id, created_at, updated_at) of an ActiveRecord object to nil?
What is the easiest way to set all 开发者_JS百科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 it's a one-time thing, you could do this in the controller:
@record.update_attributes(Hash[*@record.attributes.except('created_at','updated_at','id').map { |a| [a.first, nil] }.flatten])
I know this has been answered already. I also came across the same situation that brought up another solution.
record.dup.attributes.keep_if{|k,v| !v.nil?}
Here record is the active record object.
Model.column_names.map { |col| [col, nil] }.to_h.except(*[attrs_to_except])
精彩评论