How does one add an attribute to a model?

53,428

Solution 1

Active Record maps your tables columns to attributes in your model, so you don't need to tell rails that you need more, what you have to do is create more columns and rails is going to detect them, the attributes will be added automatically.

You can add more columns to your table through migrations:

rails generate migration AddNewColumnToMyTable column_name:column_type(string by default)

Example:

rails generate migration AddDataToPosts views:integer clicks:integer last_reviewed_at:datetime 

this will generate a file:

db/2017.....rb

Open it and add modify it if needed:

self.up
  #add_column :tablename, :column_name, :column_type
  add_column :posts, views, :integer
  add_column :posts, clicks, :integer, default: 0
end

Hope this helps.

Solution 2

Yes, the solution by @JCorcuera is applicable, but I suggest applying a little more information to Rails to fulfill our requirement. Try this approach:

rails generate migration add_columnname_to_tablename columnname:datatype

For example:

rails generate migration add_password_to_users password:string

Solution 3

If you are using the Rails 4.x you can now generate migrations with references, like this:

rails generate migration AddUserRefToProducts user:references

like you can see on rails guides

Solution 4

Just to make it even simpler you can do:

rails g migration add_something_to_model something:string something_else:integer
Share:
53,428

Related videos on Youtube

jsttn
Author by

jsttn

Updated on February 23, 2020

Comments

  • jsttn
    jsttn about 4 years

    In rails I generate a model with two strings and would like to add more. How would I go about doing this?

  • HussienK
    HussienK over 8 years
    This is definitely a nicer way to do, just make sure you get the names exactly right for it to work.
  • BenKoshy
    BenKoshy almost 8 years
    Suppose I create a rails app and have a model called User_credential. This currently has: name, and phone number. After deploying, the boss suddenly realises he wants to add address to the model. And he is demanding that I create a form which adds attributes to a model. is this possible in rails?
  • JCorcuera
    JCorcuera almost 8 years
    @BKSpurgeon One option is to use a serialise field and store the custom attributes in it. Also take a look at api.rubyonrails.org/classes/ActiveRecord/Store.html which lets you treat custom attributes like a regular ones.
  • Sarumanatee
    Sarumanatee over 7 years
    "you get the names exactly right for it to work" : I'd like to add to that, add_columnname_to_tablename has a meaning, and needs to makes sense. That might seem obvious, but I didn't think of it right away, coming from another migration tool where the migration name was never relevant.