jsurf
jsurf

Reputation: 575

Is there a difference between has_one on one model vs belongs_to on the other?

I understand that a belongs_to puts the foreign key on the declaring model, and a has_one puts it on the other model. Does that mean there is no difference in this example?

class Category
 belongs_to :blog
end

class Blog
end

class Blog
 has_one :category
end

class Category
end

The only thing I can see is that the second example's nomenclature makes a little more sense.

Upvotes: 0

Views: 107

Answers (2)

DiegoSalazar
DiegoSalazar

Reputation: 13521

Yes.

belongs_to expects the foreign key to be on its table whereas has_one expects it to be on the other:

# here the Category table will need to have a blog_id field
class Category
  belongs_to :blog
end

# the blog table won't need anything    
class Blog
  has_one :category
end

has_one under the hood is similar to has_many except it adds a LIMIT 1 clause to the sql statement when you query the table.

Upvotes: 2

CDub
CDub

Reputation: 13344

The difference lies in the database, as you've noted. The model with the belongs_to reference must contain the foreign key for the association. When using has_one, it will expect to find a foreign key on the associated model.

Upvotes: 1

Related Questions