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 
programmer...

I'll break the statement into parts:

Part 1:
Loyalty.find_by_sql

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

Part 2:
.first

Returns the first object contain in the collection returned by 
find_by_sql.

Part 3:
.recordcount

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"

Result:
 => 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.

-- 
Posted via http://www.ruby-forum.com/.

-- 
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 [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to