如何向模型添加属性?
在 Rails 中,我生成了一个带有两个字符串的模型,并想添加更多。我该怎么做呢?
In rails I generate a model with two strings and would like to add more. How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,@JCorcuera 的解决方案是适用的,但我建议在 Rails 上应用更多信息来满足我们的要求。尝试这种方法:
例如:
Yes, the solution by @JCorcuera is applicable, but I suggest applying a little more information to Rails to fulfill our requirement. Try this approach:
For example:
Active Record 将表列映射到模型中的属性,因此您无需告诉 Rails 您需要更多列,您所要做的就是创建更多列,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:
Example:
this will generate a file:
Open it and add modify it if needed:
Hope this helps.
如果您使用的是 Rails 4.x,您现在可以使用引用生成迁移,如下所示:
,就像您在 rails 指南 上看到的那样
If you are using the Rails 4.x you can now generate migrations with references, like this:
like you can see on rails guides
为了让事情变得更简单,你可以这样做:
Just to make it even simpler you can do: