source through先の関連名と異なる関連名を指定できるようにする
使用可能な関連付け
has_manyhas_one
対となる関連に指定するオプション
なし
概要
has_many ... through: ...関連などで関連名とthrough先での関連名が異なる場合にthrough先の関連名を指定する。
class Books < ApplicationRecord
belongs_to :publisher
belongs_to :author
end
class Publisher < ApplicationRecord
has_many :books
has_many :authors, through: :books
end
上記のような関連定義があり、authors関連をbusiness_partnersに変えたい場合、sourceを使って以下のようにできる。
class Publisher < ApplicationRecord
has_many :books
has_many :business_partners, through: :books, source: :author
end