可以使用条件子集进行ActiveRecord查询。例如:
Client.where(:orders_count => [1,3,5])
据推测,您可以使用多个子集执行此操作:
Client.where(:orders_count => [1,3,5], :location => ["Austin", "New York", "Chicago"])
如果您希望这两个子集相互依赖,如同多态关系,那该怎么办:
Client.where(:clientable_type => ["business", "charity", "business"], :clientable_id => [1, 1, 2])
因此,此查询会有效地查找Client.find_by(:clientable_type => "business", :clientable_id => 1)
,Client.find_by(:clientable_type => "charity", :clientable_id => 1)
和Client.find_by(:clientable_type => "business", :clientable_id => 2)
。但不是,Client.find_by(:clientable_type => "charity", :clientable_id => 2)
,因为它将链接每个数组中的第一个项目,然后链接每个数组中的第二个项目,然后是第三个项目等。
是否可以编写类似的查询?
答案 0 :(得分:0)
我可能不是100%正确,但我相信可以将两个where
条款链接在一起。这样的例子就是。
@person = Person.where(name: "David").where(age: 22)
执行此activerecord查询时,它还会发出另一个查询
因此,当执行上述acitverecord查询时,它将执行以下操作
SELECT name, age
FROM person
WHERE name = "David",
AND age = "22";
因此,据说我相信您想要的以下查询如下:
@client = Client.where(:orders_count => [1,3,5].where
(:location => ["Austin", "New York", "Chicago"]
我认为以上应该做的是检查奥斯汀,纽约和芝加哥地区orders_cont
为1,3,5的所有客户,并给你回复。
<强>更新强>
API Ruby on Rails - Where提供了以下示例:
User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
# SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
说到这里我或者提出以下内容:
Client.where(["orders_count = :orders_count and location = :location",
{orders_count "1", "3", "5" location: "Austin", "New York", "Chicago"}])
所以SQL输出我相信也会沿着以下几行。
SELECT orders_count, location
FROM orders_count, location
WHERE orders_count = "1, 3, 5",
AND location = "Austin, New York, Chicago;