Topic: Have 2 SQL queries would like only one..

I'm doing a find_by_sql using will_paginate.  One of the things I need to return to will_paginate is the number of records (wish it could just figure that out itself.. maybe in a future build)

@foo = Foo.find_by_sql("blah blah sql here"),
       :per_page => 6, :page => params[:page], :total_entries => ZZZ

Now the ZZZ is the interesting part. All it should be in @foo.size but I can't recursively call that in the same expression.  Which means I have to put the same sql statement in my code ahead of this one just to call .size on it for will_paginate.  There's got to be a better way, right?  Can I avoid:

@foo_count = Foo.find_by_sql("blah blah sql here")

@foo = Foo.find_by_sql("blah blah sql here"),
       :per_page => 6, :page => params[:page], :total_entries => @foo_count

Re: Have 2 SQL queries would like only one..

The way pagination works is it only returns the records it needs to display on one page, that is why you need to supply the total records (so it can calculate how many pages there are). I'm afraid there's no way around it. You'll need to send two queries.

However, you can use count_by_sql for better performance on the first query.

Railscasts - Free Ruby on Rails Screencasts