How does one add an attribute to a model?

后端 未结 4 609
余生分开走
余生分开走 2020-12-07 19:05

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

相关标签:
4条回答
  • 2020-12-07 19:19

    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
    
    0 讨论(0)
  • 2020-12-07 19:20

    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

    0 讨论(0)
  • 2020-12-07 19:24

    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.

    0 讨论(0)
  • 2020-12-07 19:40

    Just to make it even simpler you can do:

    rails g migration add_something_to_model something:string something_else:integer
    
    0 讨论(0)
提交回复
热议问题