145
122

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

has_one と belongs_to についての復習

Last updated at Posted at 2014-07-31

belongs_to の使い方を理解したのでメモ
has_one と belongs_to はセットで使用する。

従属する側のモデルに belongs_to を記述し、
従属させる側のモデルに has_one を記述する。

下記のような具合

idea_explanation.rb
class IdeaExplanation < ActiveRecord::Base

  belongs_to :idea                                                                                                                                                              

end
idea.rb
class Idea < ActiveRecord::Base
                                                                                                                                                              
  has_one :idea_explanation

end

上記のように書いておくとIdea モデルのオブジェクトから idea_explanation モデルオブジェクトに下記のようにアクセスできる。

irb(main):006:0> Idea.find(1).idea_explanation
  Idea Load (0.4ms)  SELECT `ideas`.* FROM `ideas` WHERE `ideas`.`id` = 1 LIMIT 1
  IdeaExplanation Load (0.4ms)  SELECT `idea_explanations`.* FROM `idea_explanations` WHERE `idea_explanations`.`idea_id` = 1 LIMIT 1
=> #<IdeaExplanation id: 1, idea_id: 1, created_at: nil, updated_at: nil>

外部のIDを持っているモデルはbelongs_to
持っていないモデルにはhas_one という理解で問題無いと思われる。

145
122
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
145
122

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?