active record with queries

can i use like this in ruby on rails

Loyalty.find_by_sql(“SELECT COUNT(id) FROM loyalties”)

And also how to take the result value?

Thank you


What happened when you tried it?
Run the command in the rails console to see what the result is.


You can do that with :

but if you insist on using find_by_sql, you can do this:
  Loyalty.find_by_sql("SELECT COUNT(id) as recordcount FROM

Play with this stuff in the console, and read the API docs, and you
won't need to ask these questions

i tried in the rails code, not in the console. can i use like dat? when i try in code, it didn’t give anythng…?

Why are you reposting exactly the same question an hour later? Have
you TRIED in the console?! Then you would KNOW if you "can use like
dat" }:-[

for getting the order of questions, so that y am repeating the same question again. i tried that in the console, now i got the correct value… but how is apply in code?

Thank you


ok fine, i just used in the rails code, now i got the same output. can u give one clarification about that query

Loyalty.find_by_sql(“SELECT COUNT(id) as recordcount FROM
loyalties”)**.first.recordcount, ** the recordcount is the count.

here what is this first.recordcount

Thank you

Dheeraj Kumar

amvis wrote in post #1037853:

ok fine, i just used in the rails code, now i got the same output. can u
give one clarification about that query

Loyalty.find_by_sql("SELECT COUNT(id) as recordcount FROM
loyalties")*.first.recordcount, * the recordcount is the count.
here what is this* first.recordcount*

Okay, I'm going to explain this to you, against my better judgement.
However, you're going to have to learn how to answer questions like this
on your own. Otherwise you're never going to become productive as a

I'll break the statement into parts:

Part 1:

This statement is designed to return the results as a collection (Array)
of objects.

Part 2:

Returns the first object contain in the collection returned by

Part 3:

This is the method that returns the attribute named in the SQL (as
recordcount). ActiveRecord will create the .recordcount method
dynamically based on the objects it receives from the database.

Again, and as was mentioned in an earlier post. This particular
technique, for this particular query, is completely unnecessary as
Loyalty.count should give you the exact same result, just as efficiently
as writing the SQL yourself.

Example Query:

ruby-1.9.3-p0 :001 > Order.count

The generated SQL:
   (0.5ms) SELECT COUNT(*) FROM "orders"

=> 2

Counting id (assuming id is the primary key of the table) should always
match COUNT(*) since id should NEVER be null.

Using .find_by_sql should be reserved as a last resort. If ActiveRecord
can give you want to want then use what it provides before resorting to
raw SQL queries.