Arel 聚合、计数、外连接?
我有一个 Fact
模型,它 has_many
:votes
。投票还有一个 user_id
字段。 我想在 Fact
模型的范围内表达以下内容:给我所有 0 票且 user_id
等于 X 的事实。
我不太明白对 Arel 足够熟悉,了解我如何解决这个问题。有想法吗?
I have a Fact
model, which has_many
:votes
. Votes also have a user_id
field.
I'd like to express the following in a scope for the Fact
model: Give me all Facts which have 0 votes with a user_id
equal to X.
I'm not quite familiar enough with Arel to understand how I might tackle this. Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是有效的:
vote_count 范围有点sqlly,但您可以根据需要链接这些查找器,您还可以使用以下命令查看底层 sql:
并且根据您的评论,您可以通过首先声明关系在纯 Arel 中执行相同的操作:
然后编写查询并将其呈现为 sql。
您可以使用运算符对列进行操作:
f[:user_id].eq(1)
然后使用它:
我确信您还可以做更多的事情来获得更优雅的语法(没有 'where 0 == ...' )。另外,我很确定 Rails3 范围在幕后使用 Arel - http://m.onkey .org/active-record-query-interface
This works:
The vote_count scope is a bit sqly but you can chain these finders however you like, you can also see the underlying sql with:
And further to your comment, you might do the same in pure Arel by first declaring the Relations:
Then composing the query and rendering it to sql.
You can act on columns with operators:
f[:user_id].eq(1)
Then using it:
I'm sure theres a lot more that you could do to get a more elegant syntax (without the 'where 0 == ...' ). Also I'm pretty sure Rails3 scopes use Arel behind the scenes - http://m.onkey.org/active-record-query-interface
我最终解决了这个问题,范围如下:
I ended up solving this problem with the following scope: