如何向模型添加属性?

发布于 2024-11-15 12:45:06 字数 48 浏览 2 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

晨曦慕雪 2024-11-22 12:45:06

是的,@JCorcuera 的解决方案是适用的,但我建议在 Rails 上应用更多信息来满足我们的要求。尝试这种方法:

rails generate migration add_columnname_to_tablename columnname:datatype

例如:

rails generate migration add_password_to_users password:string

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
笑,眼淚并存 2024-11-22 12:45:06

Active Record 将表列映射到模型中的属性,因此您无需告诉 Rails 您需要更多列,您所要做的就是创建更多列,Rails 将检测到它们,属性将自动添加。

您可以通过迁移向表中添加更多列:

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

打开它并根据需要添加修改:

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

希望这有帮助。

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.

Oo萌小芽oO 2024-11-22 12:45:06

如果您使用的是 Rails 4.x,您现在可以使用引用生成迁移,如下所示:

rails 生成迁移 AddUserRefToProducts user:references

,就像您在 rails 指南 上看到的那样

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

童话 2024-11-22 12:45:06

为了让事情变得更简单,你可以这样做:

rails g migration add_something_to_model something:string something_else:integer

Just to make it even simpler you can do:

rails g migration add_something_to_model something:string something_else:integer
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文