在 Rails 中组合条件数组
我正在使用 Rails3 beta、will_paginate gem 和 geokit gem &插件。
作为 geokit-rails 插件,似乎不支持 Rails3 范围(包括 :origin 符号是问题),我需要使用 .find 语法。
我需要以数组格式组合两组条件来代替范围:
我有一个默认条件:
conditions = ["invoices.cancelled = ? AND invoices.paid = ?", false, false]
我可能需要将以下条件之一添加到默认条件,具体取决于 UI 选择:
#aged 0
lambda {["created_at IS NULL OR created_at < ?", Date.today + 30.days]}
#aged 30
lambda {["created_at >= ? AND created_at < ?", Date.today + 30.days, Date.today + 60.days]}
#aged > 90
lamdba {["created_at >= ?", Date.today + 90.days]}
生成的查询类似于:
@invoices = Invoice.find(
:all,
:conditions => conditions,
:origin => ll #current_user's lat/lng pair
).paginate(:per_page => @per_page, :page => params[:page])
问题:
- 是否有一种简单的方法来组合这两个条件数组(如果我措辞正确)
- 虽然它不会导致问题,但是否有一种更干燥的方法来创建这些老化桶?
- 有没有办法将 Rails3 范围与 geokit-rails 插件一起使用?
感谢您抽出时间。
I'm using the Rails3 beta, will_paginate gem, and the geokit gem & plugin.
As the geokit-rails plugin, doesn't seem to support Rails3 scopes (including the :origin symbol is the issue), I need to use the .find syntax.
In lieu of scopes, I need to combine two sets of criteria in array format:
I have a default condition:
conditions = ["invoices.cancelled = ? AND invoices.paid = ?", false, false]
I may need to add one of the following conditions to the default condition, depending on a UI selection:
#aged 0
lambda {["created_at IS NULL OR created_at < ?", Date.today + 30.days]}
#aged 30
lambda {["created_at >= ? AND created_at < ?", Date.today + 30.days, Date.today + 60.days]}
#aged > 90
lamdba {["created_at >= ?", Date.today + 90.days]}
The resulting query resembles:
@invoices = Invoice.find(
:all,
:conditions => conditions,
:origin => ll #current_user's lat/lng pair
).paginate(:per_page => @per_page, :page => params[:page])
Questions:
- Is there an easy way to combine these two arrays of conditions (if I've worded that correctly)
- While it isn't contributing to the problem, is there a DRYer way to create these aging buckets?
- Is there a way to use Rails3 scopes with the geokit-rails plugin that will work?
Thanks for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
编辑方法 2
Monkey 修补
Array
类。在config/initializers
目录中创建一个名为monkey_patch.rb
的文件。现在你可以这样做:
Try this:
Edit Approach 2
Monkey patch the
Array
class. Create a file calledmonkey_patch.rb
inconfig/initializers
directory.Now you can do this:
我认为更好的方法是使用匿名范围。
在这里查看:
http://railscasts.com/episodes/112-anonymous-scopes
I think a better way is to use Anonymous scopes.
Check it out here:
http://railscasts.com/episodes/112-anonymous-scopes