如何使用 ActiveRecord 模型在日期范围之间进行搜索?

发布于 2024-08-31 08:32:47 字数 576 浏览 8 评论 0原文

我对 Ruby 和 ActiveRecord 都是新手。我目前需要修改现有的代码以在选择中添加日期范围。当前的内容是这样的:

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

现在,我需要添加一个范围,但我不确定如何执行 BETWEEN>=< = 运算符。我想我需要的是类似的东西:

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 注入攻击。

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}")

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

轻拂→两袖风尘 2024-09-07 08:32:47

我相信您可以将 Range 对象传递给 ActiveRecord 的查找并获取您想要的内容:

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

编辑:如果您使用的是 Rails 3,您可以期望使用类似的内容:

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

有关 Rails 3 Active Record 查询的更多信息,请查看:
http://railscasts.com/episodes/202-active-record -query-in-rails-3

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 } )

Edit: 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)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文