与2 ARGS活动记录总和 [英] Active Record sum with 2 args
问题描述
我在使用的ActiveRecord 3.0.3一个Rails3应用程序。
I have a Rails3 app using ActiveRecord 3.0.3.
我想获得一笔为表基于该表2子查询的字段。
I am trying to get a sum for a table based on 2 subquery fields in that table.
使用Rails控制台,我可以得到它回来与正确的值,像这样:
Using Rails Console, I can get it to come back with the correct value like so:
result = MyObject.sum(:foo, :conditions => "foo_id = #{self.id} AND bar_id = #{self.bar_id}" )
不过,我不能让它像这样的工作:
However, I could not get it to work with something like this:
result = MyObject.sum(:foo, :conditions => "foo_id = ? AND bar_id = ?", self.id, self.bar_id )
这样做会导致: 语法错误,意想不到的',',期待tASSOC
Doing so would result in : syntax error, unexpected ',', expecting tASSOC
我的提问:所以,我有一个产生正确的价值code。但我担心可能的SQL注入做这种方式?通常情况下,你会使用参数,活动记录查询,这个看起来有点更像连接。
My question: So, I have code that produces the correct value. But I'm worried about possible SQL injection doing it this way? Normally, you would use parameters with active record queries and this looks a bit more like concatenation.
我还在学习在我的方式活动记录。 感谢您的任何建议。
I'm still learning my way around Active Record. Thanks for any advice.
推荐答案
我想我只是理解了它。这是很难找到的例子这只是环绕的args括号(将它们组合到一个数组)。
I think I just figured it out. It was hard to find examples for this but just surround the args with brackets (grouping them into an array).
所以:
result = MyObject.sum(:foo, :conditions => "foo_id = #{self.id} AND bar_id = #{self.bar_id}" )
变成了:
result = MyObject.sum(:foo, :conditions => ["foo_id = ? AND bar_id = ?", self.id, self.bar_id] )
这篇关于与2 ARGS活动记录总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!