ActiveRecord: How to get all attributes of a model that can be mass-assigned?

Vincent picture Vincent · Oct 6, 2009 · Viewed 72.8k times · Source

I would like to have a list of all attribute names that can be mass assigned. I need this for a custom form builder that will not add input fields by default that cannot be mass assigned.

For example if I have the following model:

class Post < ActiveRecord::Base
  attr_protected :account

  belongs_to :author

  validates_presence_of :title, :author
end

I would like to have as a result [:author, :title].

Answer

semanticart picture semanticart · Oct 6, 2009

Post.accessible_attributes would cover it if you explicitly defined attr_accessible

Barring, that, doing something like this is clunky but works:

Post.new.attributes.keys - Post.protected_attributes.to_a