Cannot Query Parent with Many to Many Association - Rails

I have 3 models with the following structure:

class Customer
     has_many :invoices
     has_and_belongs_to_many :locations
end

class Invoice
    belongs_to :customer
end

class Location
    has_and_belongs_to_many :customers
end

I'm trying to write a query that will grab invoices that have parents associated to a specific location but the query I have come up with returns no results.

Invoice.where(customer: [locations: {id: specified_location.id}])

I'm not sure how to get this to work. Thanks in advance.

1 answer

  • answered 2018-10-11 20:11 Ilya Konyukhov

    You forgot to join your query with associated models. Also in where arguments there should be a Hash instead of Array (looks like a misprint; otherwise it will be a syntax error).

    Your call is:

    Invoice.joins(customer: :locations)
           .where(customer: { locations: { id: specified_location.id } })