Tuesday, March 6, 2012

Re: [Rails] getting find_by_sql to return the numeric value rather than an object that contains the value as an attribute

On 6 March 2012 16:23, Colin Law <clanlaw@googlemail.com> wrote:
>> def self.get_sum_for_range(unit_id,report1,report2)
>>    find_by_sql(["SELECT SUM(distance) as sum FROM reports WHERE
>> unit_id=? AND id >= ? AND id <= ?", unit_id, report1, report2]).sum
>> end
>
> I was thinking more along the lines of removing find_by_sql, something like
>
> Report.where("unit_id=? AND id >= ? AND id <= ?", unit_id, report1,
> report2).sum('distance')

+1

I tend to assume that there's some reason they've written the sql that
way (like it's to a view, legacy structure that doesn't map to a
model, or there's something more to the query and they've just posted
a minimum code sample) - and that's probably wrong of me. It the query
is *exactly* as posted, then yes, FTLOG change it to a chain of AR
clauses/scopes (is that the term for it?!)
:-)

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate