Steve
Steve

Reputation: 2666

How to find all records through a has_one through relations via an array

I am trying to find all payments that belong to an array of clients. The payments have a has_one, through bills relationship with clients.

The models include:

class Payment < ActiveRecord::Base
  belongs_to :bill
  has_one :client, through: :bill

class Client < ActiveRecord::Base
  has_many :bills
  has_many :payments, through: :bills

class Bill < ActiveRecord::Base
  belongs_to :client
  has_many :payments

I am trying to find with the following query

@payments = Payment.joins(:bills).where('bill.client_id IN (?)', [1,2,3,4])

but get a PG timeout message

tried a .includes instead of the .joins and also received a PG timeout message

and also tried

Payment.includes(:bill).where( bills: { 'client_id IN (?)', [1,2,3,4] } )

Thanks for any help.

Upvotes: 1

Views: 915

Answers (1)

smathy
smathy

Reputation: 27961

You've got your bill singular/plurals the wrong way around. When you make a string it has to be the table name, so it will be plural. When you use the hash format you use the same case as your association (singular when used from Payment). So:

Payment.joins(:bill).where( bills: { client_id: [1,2,3,4] } )

Upvotes: 4

Related Questions