LoginSignup
1
1

More than 5 years have passed since last update.

has_one :throughで結合モデルの属性で絞り込みたい場合の書き方

Posted at
  • 1人のメンバーが複数のチームに所属できる
  • 所属という結合モデルがある
  • 所属モデルが役割という属性を持っていて、その人のそのチームでの役割を表す

とした場合

models/team.rb
class Team < ActiveRecord::Base
  has_many :belongings
  has_many :members

  has_one :leader_belonging, -> { where(role: 'leader') }, class_name: 'Belonging'
  has_one :leader, through: :leader_belonging, source: :member
end
models/belonging.rb
class Belonging < ActiveRecord::Base
  belongs_to :team
  belongs_to :member
end

has_one :leader, through: :leader_belonging, source: :member というのは、振る舞いとしては team.leader_belonging.member と同じ内容を team.leader で取得できるようにしている

1
1
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
1
1