Cannot Query Parent with Many to Many Association - Rails

Cannon

New Member
#1
I have 3 models with the following structure:
Mã:
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.
Mã:
Invoice.where(customer: [locations: {id: specified_location.id}])
I'm not sure how to get this to work. Thanks in advance.
 

Admin

Administrator
Thành viên BQT
#2
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:
Mã:
Invoice.joins(customer: :locations)
       .where(customer: { locations: { id: specified_location.id } })
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top