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

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

83170 次浏览

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

Just use

Post.accessible_attributes

That will return all the attributes accessible of the class

Some of the previously mentioned answers may not apply for Rails 4.

You can use MyModel.attribute_names to get the array of table attributes, although, that might not give you mass assignable attributes, as this aspect of Rails changes with version 4 http://weblog.rubyonrails.org/2012/3/21/strong-parameters/

For Models you can use MyModel.attribute_names or MyModel.column_names.

For instances you can use MyModel.new.attribute_names.

Post.accessible_attributes.to_a.map(&:to_sym)