lesce
lesce

Reputation: 6324

Rails model has_many , belongs_to relations

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 ?

Upvotes: 24

Views: 27221

Answers (1)

Andre Bernardes
Andre Bernardes

Reputation: 1623

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.

Upvotes: 53

Related Questions