In the ActiveRecord is it mandatory to use belongs_to?

1

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

Example:

class Article < ActiveRecord::Base
  has_one :category
end

class Category < ActiveRecord::Base
  has_many :articles
end
    
asked by anonymous 07.08.2017 / 04:43

1 answer

2

There is no requirement but your example implies that a Article "belongs to" a Category . So, the correct thing is to use belongs_to: category .

In this case, belongs_to requires the category_id field in the Article template. That is also how has_many finds the records.

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

    
25.08.2017 / 09:21