Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 397
Vincent Avatar asked Oct 06 '09 14:10

Vincent


People also ask

What is mass assignment in Rails?

Mass Assignment is the name Rails gives to the act of constructing your object with a parameters hash. It is "mass assignment" in that you are assigning multiple values to attributes via a single assignment operator.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is an ActiveRecord relation object?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

What is Ruby ActiveRecord?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


2 Answers

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 
like image 63
semanticart Avatar answered Sep 27 '22 22:09

semanticart


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/

like image 45
Victor S Avatar answered Sep 27 '22 23:09

Victor S