Active Record - Record Count

I have been using ActiveRecord's find_by_sql to obtain the number of
records within a date range from a mysql database like this:

result = Xyz.find_by_sql("SELECT COUNT(*) as recordcount FROM xyz where
rdate > '#{start_date}' and rdate < '#{end_date}'")[0].recordcount

The problem with the above approach is that it is tied to mysql. Is
there a way that I can accomplish the above in a database independent
way?

Thanks for any input.

       ... doug

Something like:

    Xyz.where("rdate BETWEEN ? and ?", start_date, end_date).count

or:

    Xyz.where(rdate: start_date..end_date).count

ought to work just fine. The latter is shorter, but I think I'd favor
the clarity of the former (or maybe I'm just not sufficiently used to
that syntax yet). Check out:

  http://guides.rubyonrails.org/active_record_querying.html

for all sorts of useful ActiveRecord query methods.

-Dave

Doug Jolley wrote in post #1068482:

I have been using ActiveRecord's find_by_sql to obtain the number of
records within a date range from a mysql database like this:

result = Xyz.find_by_sql("SELECT COUNT(*) as recordcount FROM xyz where
rdate > '#{start_date}' and rdate < '#{end_date}'")[0].recordcount

The problem with the above approach is that it is tied to mysql. Is
there a way that I can accomplish the above in a database independent
way?

That's not the only problem with this style of query. There's also
potentially serious security problems with it as well.

You should read the guide on securing Rails applications. Specifically
for this case read up on SQL Injection:

http://guides.rubyonrails.org/security.html#sql-injection