Rails3/ActiveRecord:选择带有参数的总和?

发布于 2024-11-03 06:08:58 字数 724 浏览 1 评论 0原文

在 SQLite 中给出以下(已经简化的)查询:

def self.calculate(year, month, user_id, partner_id)
  where(':user_id = entries.user_id OR :partner_id = entries.user_id', {    
      :user_id => user_id,
      :partner_id => partner_id
  }).
  where('entries.date <= :last_day', { 
      :last_day => Date.new(year, month, 1).at_end_of_month
  }).
  select('sum(case when joint = "f" and user_id = :user_id then amount_calc else 0 end) as sum_single' , {    
      :user_id => user_id 
  }).
  group("strftime('%Y-%m', date)")
end

完整查询具有不同 case when 语句的更多总和,其中一些取决于它是 user_id 还是 Partner_id。不幸的是,Rails 抱怨 select 没有像 where 那样使用第二个参数进行替换。有没有办法在不运行两个查询(一个针对 user_id,一个针对partner_id)的情况下实现我想要的目标?

Give the following (already simplified) query in SQLite:

def self.calculate(year, month, user_id, partner_id)
  where(':user_id = entries.user_id OR :partner_id = entries.user_id', {    
      :user_id => user_id,
      :partner_id => partner_id
  }).
  where('entries.date <= :last_day', { 
      :last_day => Date.new(year, month, 1).at_end_of_month
  }).
  select('sum(case when joint = "f" and user_id = :user_id then amount_calc else 0 end) as sum_single' , {    
      :user_id => user_id 
  }).
  group("strftime('%Y-%m', date)")
end

The full query has more sums with different case when statements and some of them depend on whether it is user_id oder partner_id. Unfortunately, Rails complains as select does not take the second parameter with the substitutions like where does. Is there any way to achieve what I want without running two queries, one for user_id and one for partner_id?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风月客 2024-11-10 06:08:58

人们可能会如此盲目......而不是:

select('sum(case when joint = "f" and user_id = :user_id then amount_calc else 0 end) as sum_single' , {    
  :user_id => user_id 
}).

只构建字符串:

select('sum(case when joint = "f" and user_id = ' + user_id.to_s + ' then amount_calc else 0 end) as sum_single').

因为没有人回答,这是为了档案:)

编辑:抱歉,请注意:如下所述,这是容易受到攻击的。

One can be so blind....instead of:

select('sum(case when joint = "f" and user_id = :user_id then amount_calc else 0 end) as sum_single' , {    
  :user_id => user_id 
}).

just build the string:

select('sum(case when joint = "f" and user_id = ' + user_id.to_s + ' then amount_calc else 0 end) as sum_single').

As nobody answered, this is for the archives :)

Edit: Sorry, beware of that: as noted below, this is vulnerable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文