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]
.
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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 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.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With