简体   繁体   English

Arel Aggregations,Count,Outer Join?

[英]Arel Aggregations, Count, Outer Join?

I have a Fact model, which has_many :votes . 我有一个Fact模型,其中has_many :votes Votes also have a user_id field. 投票还有一个user_id字段。 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. 我想在Fact模型的范围内表达以下内容:给我所有有0票且user_id等于X的事实。

I'm not quite familiar enough with Arel to understand how I might tackle this. 我对Arel不太熟悉,无法理解如何解决这个问题。 Ideas? 想法?

This works: 这有效:

class Fact < ActiveRecord::Base
  scope :by_user, lambda { |id| joins(:user).where('users.id == ?', id).readonly(false)    }
  scope :vote_count, lambda { |count| where('? == (select count(fact_id) from votes where votes.fact_id == facts.id)', count)}
end

Fact.by_user(1).vote_count(0)

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: vote_count范围有点sqly,但你可以链接这些查找器,但你也可以看到底层的sql:

Fact.by_user(1).vote_count(0).to_sql

And further to your comment, you might do the same in pure Arel by first declaring the Relations: 除了你的评论之外,你可以通过首先声明关系来在纯Arel中做同样的事情:

f = Arel::Table.new(:facts)
v = Arel::Table.new(:votes)
u = Arel::Table.new(:users)

Then composing the query and rendering it to sql. 然后编写查询并将其呈现给sql。

sql = f.join(u).on(f[:user_id].eq(1)).where('0 == (select count(fact_id) from votes where votes.fact_id == facts.id)').to_sql

You can act on columns with operators: f[:user_id].eq(1) 您可以使用运算符对列进行操作: f[:user_id].eq(1)

Then using it: 然后使用它:

Fact.find_by_sql(sql)

I'm sure theres a lot more that you could do to get a more elegant syntax (without the 'where 0 == ...' ). 我相信你可以做更多的事情来获得更优雅的语法(没有'where 0 == ...')。 Also I'm pretty sure Rails3 scopes use Arel behind the scenes - http://m.onkey.org/active-record-query-interface 另外我很确定Rails3范围在幕后使用Arel - http://m.onkey.org/active-record-query-interface

我最终用以下范围解决了这个问题:

  scope :not_voted_on_by_user, lambda {|user_id| select("distinct `facts`.*").joins("LEFT JOIN `votes` ON `facts`.id = `votes`.fact_id").where(["votes.user_id != ? OR votes.user_id IS NULL",user_id])}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM