K
K
Kana2016-09-10 17:17:08
Ruby on Rails
Kana, 2016-09-10 17:17:08

When should belongs_to be set, and when should has_one?

There is a Page model that is needed for a text page.
There is a Feature model that is needed for the icons on the main page. It may lead to some page, or it may not lead. You just need the page_id field, which can be null (it's already created by the migration).
The question is, should you do

class Feature < ApplicationRecord
  has_one :page
end

or
class Feature < ApplicationRecord
  belongs_to :page
end

page_id works in any case, the question is only about the cleanliness of the code.
There is no need to access feature in page, so there is no feature_id field in the table and no has_one/belongs_to relationships in the model.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Kostin, 2016-09-10
@kana-desu

belongs_to means the Page has many Features. Those. for feedback, the Page must have

class Page < ApplicationRecord
  has_many :features
end

Thus it is possible to call
page = Page.first
page.features

If there is no such relationship, then you should use has_one following your logic.

K
kliss, 2016-09-12
@kliss

belongs_to is placed where there is a field for the ID. If there is a page_id in the features table, then this feature belongs_to page. And if feature_id is in pages, then feature has_one page (has_many pages) + page belongs_to feature

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question