让我们有一个 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
也将经理注入(inject) 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 加载数据:
my_query.take(10)
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
关于ruby-on-rails-4 - Arel:来自 Arel::SelectManager 与连接的事件关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840944/