开发者

Active Record sum with 2 args

开发者 https://www.devze.com 2023-01-28 19:28 出处:网络
I have a R开发者_如何学Cails3 app using ActiveRecord 3.0.3. I am trying to get a sum for a table based on 2 subquery fields in that table.

I have a R开发者_如何学Cails3 app using ActiveRecord 3.0.3.

I am trying to get a sum for a table based on 2 subquery fields in that table.

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 )

Doing so would result in : syntax error, unexpected ',', expecting tASSOC

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.


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).

So:

result = MyObject.sum(:foo, :conditions => "foo_id = #{self.id} AND bar_id = #{self.bar_id}" )

becomes:

result = MyObject.sum(:foo, :conditions => ["foo_id = ? AND bar_id = ?", self.id, self.bar_id] )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号