Is it mandatory to use belongs_to in Activerecord?

Asked

Viewed 188 times

1

It is mandatory that in order to have an association between two models, I have belongs_to and has_one? Or it is possible to use only has_one/has_many between the two models, when not necessarily any of the models belong to some other?

Example:

class Article < ActiveRecord::Base
  has_one :category
end

class Category < ActiveRecord::Base
  has_many :articles
end
  • You can better understand in the official guide: /Association Basics

  • @Danilocândido came up this reading precisely the Rails Guides :/ The Migration of the example for has_one for example corresponds to t.belongs_to :supplier.

1 answer

2


There is no obligation but his example suggests that Article "belongs to" a Category. So the right thing to do is to use belongs_to :Category.

In that case, the belongs_to requires the existence of the field category_id on the model Article. Which is also the way that the has_many finds the records.

However, if you wish to use the has_one so that in the future it can become has_many, no problem. You will need to use the intermediate table article_categories that will link between the two models and there will be no need to have the field category_id in the Article.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.