views:

16

answers:

2

Hi

In Rails 2.3.8 there is a class method ActiveRecord::Base.count_by_sql which allows to perform custom SELECT count(*) .... Is it save to execute customized SELECT sum(...) ... query with this method? If not, what should be done to execute such a query? Is ActiveRecord::Base.connection.execute the only option?

Thanks.

EDIT: Query I want to perform has another query nested. That's why I believe methods from ActiveRecord::Calculations are not sufficient.

A: 

Check ActiveRecord::Calculations. The API docs are here.

You can do something like this (assuming you have User model):

User.maximum(:updated_at)
# Generates:
# SELECT max(`users`.updated_at) AS max_updated_at FROM `users`
Swanand
Thanks for answer, but it is not enough in my case. I haven't mention that clear enough before, but I need to pass raw SQL (at least I think so). My query has another query nested, it looks like this: `SELECT MAX(...) FROM (here goes nested query I can't get rid of)`. That's why I need a method like `count_by_sql`.
skalee
A: 

select_value from ActiveRecord::ConnectionAdapters::DatabaseStatements module is the answer. It returns the value present in the first column of the first row returned by query. select_value returns String, so conversion may be necessary.

Example:

ActiveRecord::Base.connection.select_value("Some complicated sql")
skalee