user1364684
user1364684

Reputation: 800

Differences between "has_one" and "belongs_to" in Rails

What is the difference? advantages and disadvantages? It is a bit confuse for me.

Thanks.

Upvotes: 2

Views: 240

Answers (3)

coorasse
coorasse

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

Marlin Pierce
Marlin Pierce

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

tmaximini
tmaximini

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

Related Questions