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 ?
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 ?
You do need to manually add the
user_id
column to theProduct
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 theproducts
table. With the column properly named (user_id), Rails will know that's your foreign key.