且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为模型添加属性?

更新时间:2023-12-02 23:01:58

Active Record 将你的表列映射到模型中的属性,所以你不需要告诉 rails 你需要更多,你要做的就是创建更多的列和轨道将检测到它们,属性将自动添加.

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)

例子:

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

这将生成一个文件:

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

希望这会有所帮助.