Ruby-on-rails Rails 模型 has_many ,belongs_to 关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8742633/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:34:27  来源:igfitidea点击:

Rails model has_many , belongs_to relations

ruby-on-railsrubyruby-on-rails-3

提问by lesce

I have 2 models

我有2个模型

 class User < ActiveRecord::Base
   has_many :products
 end

class Product < ActiveRecord::Base
  belongs_to :user
end

Do I need to add a column user_id to the Product table or does rails add it by default ?

我需要在 Product 表中添加列 user_id 还是 rails 默认添加它?

回答by Andre Bernardes

You do need to manually add the user_idcolumn to the Productmodel. If you haven't created your model yet, add the reference in the column list to the model generator. For example:

您确实需要手动将user_id列添加到Product模型中。如果您尚未创建模型,请将列列表中的引用添加到模型生成器。例如:

rails generate model Product name:string price:decimal user:references

rails generate model Product name:string price:decimal user:references

Or, if your Productmodel already exists what you have to do is:

或者,如果您的Product模型已经存在,您必须做的是:

rails g migration addUserIdToProducts user_id:integer

rails g migration addUserIdToProducts user_id:integer

That will generate a migration that properly add the user_idcolumn to the productstable. With the column properly named (user_id), Rails will know that's your foreign key.

这将生成一个迁移,将user_id列正确添加到products表中。正确命名列 (user_id) 后,Rails 将知道这是您的外键。