What happened when you tried it?
Run the command in the rails console to see what the result is.
Colin
You can do that with :
Loyalty.count
but if you insist on using find_by_sql, you can do this:
Loyalty.find_by_sql("SELECT COUNT(id) as recordcount FROM
loyalties").first.recordcount
Play with this stuff in the console, and read the API docs, and you
won't need to ask these questions
:-/
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" }:-[
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/dFmE-twrCTkJ.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
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/.