如何向模型添加属性? [英] How does one add an attribute to a model?

查看:33
本文介绍了如何向模型添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 rails 中,我生成了一个带有两个字符串的模型,并想添加更多.我该怎么做?

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

推荐答案

Active Record 将你的表列映射到你模型中的属性,所以你不需要告诉 rails 你需要更多,你要做的就是创建更多的 column 和 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

希望这会有所帮助.

这篇关于如何向模型添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆