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 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])