Ruby-on-rails 如何向模型添加属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6373202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does one add an attribute to a model?
提问by jsttn
In rails I generate a model with two strings and would like to add more. How would I go about doing this?
在 rails 中,我生成了一个带有两个字符串的模型,并希望添加更多字符串。我该怎么做呢?
回答by vishB
Yes, the solution by @JCorcuera is applicable, but I suggest applying a little more information to Rails to fulfill our requirement. Try this approach:
是的,@JCorcuera 的解决方案是适用的,但我建议将更多信息应用于 Rails 以满足我们的要求。试试这个方法:
rails generate migration add_columnname_to_tablename columnname:datatype
For example:
例如:
rails generate migration add_password_to_users password:string
回答by JCorcuera
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.
Active Record 将您的表列映射到模型中的属性,因此您不需要告诉 rails 您需要更多,您需要做的是创建更多列并且 rails 将检测它们,属性将自动添加。
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.
希望这可以帮助。
回答by Paulo Fidalgo
If you are using the Rails 4.x you can now generate migrations with references, like this:
如果您使用的是 Rails 4.x,您现在可以使用引用生成迁移,如下所示:
rails generate migration AddUserRefToProducts user:references
rails 生成迁移 AddUserRefToProducts user:references
like you can see on rails guides
就像你在导轨上看到的那样
回答by Garrett O'Grady
Just to make it even simpler you can do:
只是为了让它更简单,你可以这样做:
rails g migration add_something_to_model something:string something_else:integer

