mahu mahu - 4 months ago 5x
Ruby Question

Ruby build .where over two classes

I'm in trouble building my

to retrieve specific Values.

I have this hierarchy:


--has_many Projects

---has_many Tickets

I want to retrieve all Tickets by a customer ID as an ActiveRecord::Relation.

My idea was this loop (c is the customer from whom I want the tickets):

customer_projects = Project.where(:customer_id =>
tickets =, anything)
customer_projects.each do |cp|
project_tickets = Ticket.where(:project_id =>"DATE(created_at) >= ?", report.start_time).where("DATE(created_at) <= ?", report.end_time)

I am neither sure where to write for "anything" as table argument, nor if this even works. I'd prefer a "simple"
that could retrieve all tickets.


You don't need all this hassle. You have the through method to do it for you.

# customer.rb
has_many :tickets, through: projects

# ticket.rb
has_many :customers, through: projects

This way, you can do: