Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 attributes (except id, created_at, updated_at) of an ActiveRecord object to nil?

like image 572
ben Avatar asked Jan 06 '11 08:01

ben


1 Answers

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

like image 161
lwe Avatar answered Oct 26 '22 23:10

lwe