Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails model has_many , belongs_to relations

Tags:

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 ?

like image 345
lesce Avatar asked Jan 05 '12 12:01

lesce


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is a polymorphic relationship Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


1 Answers

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.

like image 74
Andre Bernardes Avatar answered Sep 26 '22 02:09

Andre Bernardes