我如何搜索之间的日期范围,使用ActiveRecord模型? [英] How Do I Search Between a Date Range, Using the ActiveRecord Model?

查看:104
本文介绍了我如何搜索之间的日期范围,使用ActiveRecord模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Ruby和ActiveRecord的。我现在有一个需要修改和code片存在添加日期范围的选择。目前这块是这样的:

I am new to both Ruby and ActiveRecord. I currently have a need to modify and existing piece of code to add a date range in the select. The current piece goes like this:

ReportsThirdparty.find(:all, :conditions => {:site_id=>site_id, :campaign_id=>campaign_id, :size_id=>size_id})

现在,我需要添加一个范围,但我不知道该怎么办了> = < = 运营商。我想我需要的是类似于:

Now, I need to add a range, but I am not sure how to do the BETWEEN or >= or <= operators. I guess what I need is something similar to:

ReportsThirdparty.find(:all, :conditions => {:site_id=>site_id, :campaign_id=>campaign_id, :size_id=>size_id, :row_date=>"BETWEEN #{start_date} AND #{end_date}")

即使这没有工作,我知道,在这里使用插值会离开我受到SQL注入攻击。

Even if this did work, I know that using interpolation here would leave me subject to SQL injection attacks.

推荐答案

我相信你可以传递一个Range对象的ActiveRecord的发现,并得到你想要的东西:

I believe you can pass a Range object to ActiveRecord's find and get what you want:

ReportsThirdParty.find(:all, 
  :conditions => { 
    :site_id => site_id, 
    :campaign_id => campaign_id, 
    :size_id => size_id, 
    :row_date => start_date..end_date } )

编辑:如果您使用的Rails 3,你可以指望用类似的东西:

If you're using Rails 3 you can expect to use something similar to:

ReportsThirdParty.where( 
  :site_id => site_id, 
  :campaign_id => campaign_id, 
  :size_id => size_id, 
  :row_date => start_date..end_date)

有关Rails 3的活动记录查询的详细信息,请查看:
 <一href="http://railscasts.com/episodes/202-active-record-queries-in-rails-3">http://railscasts.com/episodes/202-active-record-queries-in-rails-3

For more information on Rails 3 Active Record queries check out:
http://railscasts.com/episodes/202-active-record-queries-in-rails-3

这篇关于我如何搜索之间的日期范围,使用ActiveRecord模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆