ActiveRecord: How to get all attributes of a model that can be mass-assigned?
Ruby on-RailsActiverecordRuby on-Rails Problem Overview
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]
.
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
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
Solution 2 - Ruby on-Rails
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/
Solution 3 - Ruby on-Rails
For Models you can use MyModel.attribute_names
or MyModel.column_names
.
For instances you can use MyModel.new.attribute_names
.
Solution 4 - Ruby on-Rails
Solution 5 - Ruby on-Rails