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

Ruby on-RailsActiverecord

Ruby 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

Just use

Post.accessible_attributes

That will return all the attributes accessible of the class

Solution 5 - Ruby on-Rails

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVincentView Question on Stackoverflow
Solution 1 - Ruby on-RailssemanticartView Answer on Stackoverflow
Solution 2 - Ruby on-RailsVictor SView Answer on Stackoverflow
Solution 3 - Ruby on-RailsScudellettiView Answer on Stackoverflow
Solution 4 - Ruby on-RailsAntoineView Answer on Stackoverflow
Solution 5 - Ruby on-RailsRajesh PaulView Answer on Stackoverflow