aris
July 12, 2012, 9:18pm
1
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
djames
July 12, 2012, 9:33pm
2
On Thu, Jul 12, 2012 at 3:18 PM, Doug J. [email protected]
wrote:
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?
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:
Active Record Query Interface — Ruby on Rails Guides
for all sorts of useful ActiveRecord query methods.
-Dave
–
Dave A., Cleared/Remote Ruby on Rails Freelancer
(NoVa/DC/Remote); see www.DaveAronson.com , and blogs at
www.Codosaur.us , www.Dare2XL.com , www.RecruitingRants.com
djames
July 12, 2012, 10:23pm
3
Doug J. 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:
Securing Rails ApplicationsThis manual describes common security problems in web applications and how to avoid them with Rails.After reading this guide, you will know: All countermeasures that are highlighted. The concept of sessions in Rails, what...