You cannot “add” a model attribute; you do this by creating a migration file and launching it. Rails determines which model-based attributes are based on columns in the database. However, you need to add a row to the model for the attribute whitelist if you want to update it with a mass assignment. This is why you often see this line in activerecord models:
attr_accessible :name
But it is optional and not necessary to add an attribute.
To add a new attribute to your model, first create a migration with:
rails g migration AddAddressToPerson address:string
This will create a migration file in the db / migration / directory. (The forms "AddXXXToYYY" and "RemoveXXXFromYYY" are understood as rails to indicate "add (or remove) a new column to model XXX", see the Documentation). In this case, I added an attribute called address , which is a string, but you can change it the way you want.
Then, to actually upgrade the database, you need to migrate using rake :
rake db:migrate
Finally, if you want to allow bulk assignment to this attribute, add this attribute to the attr_accessible argument attr_accessible :
attr_accessible :name, :address
That should do it.
Chris salzberg
source share