Rails3/ActiveRecord:选择带有参数的总和?
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
人们可能会如此盲目......而不是:
只构建字符串:
因为没有人回答,这是为了档案:)
编辑:抱歉,请注意:如下所述,这是容易受到攻击的。
One can be so blind....instead of:
just build the string:
As nobody answered, this is for the archives :)
Edit: Sorry, beware of that: as noted below, this is vulnerable.