mahu mahu - 1 year ago 42
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: