Reputation: 800
What is the difference? advantages and disadvantages? It is a bit confuse for me.
Thanks.
Upvotes: 2
Views: 240
Reputation: 5528
You put belongs_to in the table with the foreign key and has_one in the referenced table when the relation is 1-1.
You put belongs_to in the table with the foreign key and has_many in the referenced table when the relation is 1-n
Upvotes: 6
Reputation: 10079
The belongs to is on the table with the foreign key. For the following:
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
The profiles table needs to have a user_id field to reference the record in the users table.
Knowing which to be belongs_to and which to be has_one is something many people struggle with. Generally, if the has_one might likely become a has_many, then that's the side which needs to be has_one.
Upvotes: 6
Reputation: 8503
You will need both. You one on the one class, and the other on to the class you want to connect.
e.g.
Class User
has_one :profile
end
Class Profile
belongs_to :user
end
After setting up the relation properly, the advantage is that you can access them using user.profile
or profile.user
.
Upvotes: 4