Active Record sum with 2 args
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] )
精彩评论