Company has_many :agents, Agent belongs_to :company.
Agent has_many :comments, Comment belongs_to both :agent and :business.
Business has_many :comments.
What ActiveRecord query finds all the businesses with a comment written by an agent of the company?
I can get all the comments for all the agents of a company:
@company.agents.joins(:comments)
And using that query I can pluck all the business_ids that are commented on by company agents:
@company.agents.joins(:comments).pluck(:business_id)
(So if nothing else works I could get the desired list of businesses using a second query into Business given an array of IDs.)
However I cannot seem to extend the association chain in a single query to includes the Businesses, eg, a query that finds the Business record for each business commented upon by company agents, eg something like:
@company.agents.joins(:comments).joins(:business)
# Can't join 'Agent' to association named 'businesses'
EDIT:
Tried @company.agents.joins(:comments => :business)
as suggested by Jon in the comments. That works if doing a .count() or a .pluck().
If need to also query by Business fields, that can be done with:
@company.agents.joins(:comments => :business).where(:businesses => {:account_status => :active})
join
onto theagents
scope. Have you tried doing something like this:@company.agents.joins(:comments => :business)
? – Jon