简体   繁体   中英

Conditions on has_many through

I have three classes TeamMember , Service and ServiceTeamMember

I have

class Service
  has_many :service_team_members
  has_many :team_members, through: :service_team_members
end

class ServiceTeamMember
  belongs_to :service
  belongs_to :team_member
end

class TeamMember
  has_many :service_team_members
  has_many :services, through: :service_team_members
end

Now in a certain area of my site I want to eager load departments, where a department is a top level service, I'm using ancestry so all you need to know is a department is a service with ancestry of NULL

So I need an actual association so I can eager load it rather than a scope.

I've tried adding it as such

has_many :departments, -> { where(ancestry: nil) }, through: :service_team_members, source: :service

But I get the following error

Mysql2::Error: Unknown column 'services.ancestry' in 'where clause': SELECT `service_team_members`.* FROM `service_team_members`  WHERE `services`.`ancestry` IS NULL AND `service_team_members`.`team_member_id` IN (28, 32)

So rails is applying my condition to the join table rather than the table I want. How can I get around this, I assume it's a simple solution and I'm missing something obvious.

只需更改source: :service通过source: :team_member

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM