【发布时间】:2017-08-23 04:57:23
【问题描述】:
以下型号,
class User < ActiveRecord::Base
has_many :addresses
# Has an attribute named active
end
class Address < ActiveRecord::Base
# Has an attribute named city
end
如何在对 DB 的单个查询中获取所有 users where active: true 并为每个用户仅包含 addresses where city: Foo?
注意:如果用户没有city 为“Foo”的地址,则他们仍必须包含在结果中,addresses 为空。
示例数据
test=# select * from users;
id | name | active
----+------+--------
1 | Jack | t
2 | John | t
3 | Jane | t
4 | Jill | f
(4 rows)
test=# select * from addresses;
id | user_id | street | city
----+---------+--------------+------
1 | 1 | Foo Street | Foo
2 | 1 | Bar Street | Bar
3 | 2 | Bar Street | Bar
4 | 4 | Foo Street | Foo
5 | 1 | Foo Street 1 | Foo
(5 rows)
预期结果
id | name | street | city
----+------+--------------+------
1 | Jack | Foo Street 1 | Foo
1 | Jack | Foo Street | Foo
2 | John | |
3 | Jane | |
(4 rows)
下面的 SQL 查询可以产生该结果,但我想不出一种方法让 AR 生成该查询或任何其他查询来产生上述结果。
select users.id, name, street, city from users left join lateral (
select * from addresses where addresses.user_id = users.id and city = 'Foo'
) addr on true
where users.active;
【问题讨论】:
-
这是
User.includes(:addresses).where(active: true).where(addresses: {city: 'Foo'})你在找什么吗? -
排除在“Foo”中没有任何地址的用户。
-
您的要求不是很清楚,各种答案都不能产生您想要得到的结果。考虑展示一些具有各种地址组合的用户记录的示例,并显示所需的过滤结果。
-
添加了一些例子。
标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord