Rails model has_many , belongs_to relations

2020-05-17 06:58发布

I have 2 models

 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 ?

1条回答
疯言疯语
2楼-- · 2020-05-17 07:52

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 generate model Product name:string price:decimal user:references

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

rails g migration addUserIdToProducts user_id:integer

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.

查看更多
登录 后发表回答