Rails 3 - where has_many clause through association

Hi,

I have a little problem with asking where for has_many: through concatenation ...

My setup is as follows:

PurchaseOrderAddressAssignment:

belongs_to :address

belongs_to :purchase_order

The address:

has_many :purchase_order_address_assignments

has_many :purchase_orders, :through => :purchase_order_address_assignments

PurchaseOrder:

has_many :purchase_order_address_assignments

has_many :addresses, :through => :purchase_order_address_assignments

My suggestion is where:

PurchaseOrder.where("addresses.id = 168 and addresses.id = 169").includes(:addresses)

Returns 0 records ... but must be at least 1 ...

PurchaseOrder.where(:baan_id => "KD0005756").first.address_ids

Returns [168, 169, 170, 327]

... I think I'm too stupid to solve this little problem: - /

Can someone tell me what I'm doing wrong here?

thank,

Michael

+5
source share
2 answers

In this case, I would probably perform a custom search method.

class PurchaseOrder < ActiveRecordBase
  def self.with_addresses(*args)
    values = args.flatten.uniq

    # Note use :joins instead of :includes if you don't
    # want the addresses data
    includes(:addresses)
    where(:addresses => {:id => values})
    group("purchase_orders.id")
    having("count(ad‌​dresses.id)=#{values.size}")
  end
end

I am sure this will work.

Here's a similar answer that helps explain the query.

+9

, PurchaseOrder, addresses id

:

PurchaseOrder.where(addresses: {id: [168, 169]}).includes(:addresses)
+3

All Articles