jaamun
jaamun

Reputation: 181

ActiveRecord Ruby on Rails Select vs FInd_by_sql

I would like to use ActiveRecord interface for a project. I have a function in Ruby, call it "get_val." Currently, I have

Object.find_by_sql("SELECT SUM(miles * gas * tires * get_val) AS calculation FROM table")

I would like to get this into ActiveRecord format, but I don't think I am allowed to use aggregate functions in 'select' function, and I'm not sure how to use 'calculate' function properly.

Additionally, I would like to add multiple where clauses, so my follow-up question is: Can I string together ActiveRecord functions in Rails and have it execute as a single SQL query? Particularly, can I string together 'find_by_sql' with 'where' if I wanted to?

NOTE: I am developing an old application, so I am using Rails 3, just in case ActiveRecord syntax has changed drastically.

Upvotes: 0

Views: 1283

Answers (1)

ctide
ctide

Reputation: 5257

You can chain off of select (http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-select):

Object.select("SUM(miles * gas * tires * get_val) AS calculation")

But not find_by_sql.

Upvotes: 2

Related Questions