如何使用 ActiveRecord 模型在日期范围之间进行搜索?
我对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您可以将 Range 对象传递给 ActiveRecord 的查找并获取您想要的内容:
编辑:如果您使用的是 Rails 3,您可以期望使用类似的内容:
有关 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:
Edit: If you're using Rails 3 you can expect to use something similar to:
For more information on Rails 3 Active Record queries check out:
http://railscasts.com/episodes/202-active-record-queries-in-rails-3