你好,
我对has_many上的where查询有一点问题:通过关联......
我的设置如下:
PurchaseOrderAddressAssignment:
belongs_to :address
belongs_to :purchase_order
地址:
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
我的where子句:
PurchaseOrder.where("addresses.id = 168 and addresses.id = 169").includes(:addresses)
返回0记录......但应该至少有1 ...
PurchaseOrder.where(:baan_id => "KD0005756").first.address_ids
返回[168,169,170,327]
......我觉得我太愚蠢了,无法解决这个小问题: - /
有人能告诉我这里的错误吗?
THX,
迈克尔
答案 0 :(得分:10)
在这种情况下,我可能会做一个自定义查找器方法。
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(addresses.id)=#{values.size}")
end
end
我很确定这应该有效。
这是一个有助于解释查询的similar answer。
答案 1 :(得分:3)
所以你想要PurchaseOrder
的{{1}}在某个id的列表中
试试这个:
addresses