Rails 模型 has_many ,belongs_to 关系 [英] Rails model has_many , belongs_to relations

查看:58
本文介绍了Rails 模型 has_many ,belongs_to 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型

 class User < ActiveRecord::Base
   has_many :products
 end

class Product < ActiveRecord::Base
  belongs_to :user
end

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

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

推荐答案

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

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

rails 生成模型 Product name:string price:decimal user:references

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

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

rails g 迁移 addUserIdToProducts user_id:integer

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

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

这篇关于Rails 模型 has_many ,belongs_to 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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