让我们有一个 Rails 4.2.x 应用程序,我们有两个表 posts 和authors,我们想使用 Arel 来获取由 name == 'Karl' 的作者撰写的帖子。
(在本例中,我们可以对 Active Record 连接感到满意,但这只是为了使示例保持简单。)
posts = Arel::Table.new :posts
authors = Arel::Table.new :authors
my_query = posts.project(Arel.star)
.join(authors)
.on(posts[:author_id].eq(authors[:id]))
.where(authors[:name].eq('Karl'))
> my_query.class
=> Arel::SelectManager
现在我们可以通过执行以下操作来获取帖子数组(Array 类):
> Post.find_by_sql my_query
[master] Post Load (3.1ms) SELECT * FROM "posts" INNER JOIN "authors"
ON "posts"."author_id" = "authors"."id"
WHERE "authors"."name" = 'Karl'
=> [#<Post:0x005612815ebdf8
id: 7474,
...
]
所以我们确实得到了一组帖子,而不是活动记录关系:
> Post.find_by_sql(my_query).class
=> Array
同时将管理器注入 Post.where 也行不通
> Post.where my_query
=> #<Post::ActiveRecord_Relation:0x2b13cdc957bc>
> Post.where(my_query).first
ActiveRecord::StatementInvalid: PG::SyntaxError:
ERROR: subquery must return only one column
SELECT "posts".* FROM "posts"
WHERE ((SELECT * FROM "posts" INNER JOIN "authors" ON "posts"."author_id" = "authors"."id" WHERE "authors"."name" = 'Karel'))
ORDER BY "posts"."id" ASC LIMIT 1
我想我一定错过了什么。简而言之:如何从像上面的 my_query 这样的选择管理器(或完成相同操作的另一个选择管理器)获取活动记录关系。
您无法从 Arel::SelectManager 获取 ActiveRecord::Relation,也无法从 sql 字符串获取 ActiveRecord::Relation。有两种方法可以通过 ActiveRecord 加载数据:
-
在 Arel 中执行所有查询逻辑。在这种情况下,您无法使用任何 ActiveRecord::Relation 方法。但你在 Arel 中有相同的功能。在您的示例中,您可以通过 Arel 设置限制:
my_query.take(10)
-
另一种方法是在 ActiveRecord::Relation 方法中使用 Arel。您可以像这样重写您的查询:
posts = Arel::Table.new :posts
authors = Arel::Table.new :authors
join = posts.join(authors).
on(posts[:author_id].eq(authors[:id])).
join_sources
my_query = Post.
joins(join).
where(authors[:name].eq('Karl'))
> my_query.class
=> ActiveRecord::Relation
在这种情况下你可以使用my_query
作为 ActiveRecord::Relation
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)