21
12

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.

ActiveRecordのhas_manyメソッドのsourceオプションについて

Posted at

##きっかけ
アソシエーション名に被りが生じてしまい、違う名前をつけたアソシエーション名と関連先テーブルが異なる名前になったため、sourceオプションを省略することができなくなったため、改めて調べる必要が生じた

##具体例
ユーザーは複数(has_many)の質問をしている
質問はいずれかのユーザーに所属(belongs_to)している

class User < ActiveRecord::Base
has_many :answered_questions, through: :answers, source: :question
end

##解説
以上の具体例は、下記の意味と同じになる

class User < ActiveRecord::Base
has_many :questions, through: :answers
end

つまり、関連先テーブル名とアソシエーション名が同じ場合は、sourceオプションは省略することができる。
しかし、異なる場合は、source: :モデル名にて関連先テーブル名を書かなければならない

21
12
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
21
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?