mahu mahu - 6 months ago 8
Ruby Question

Ruby build .where over two classes

I'm in trouble building my

.where
to retrieve specific Values.

I have this hierarchy:

-Customer

--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 => c.id)
tickets = ActiveRecord::Relation.new(Ticket, anything)
customer_projects.each do |cp|
project_tickets = Ticket.where(:project_id => cp.id).where("DATE(created_at) >= ?", report.start_time).where("DATE(created_at) <= ?", report.end_time)
tickets.insert(project_tickets)
end


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

Answer

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:

@customer.tickets
@ticket.customers