我正在寻找基于任意数量的查询参数过滤返回到 Rails 视图的记录的最佳方法,例如:
http://localhost:3000/foo?some_field=fubar&this_field_left_blank=&a_third_field=bar
我目前在做什么
我找到并使用了has_scope
gem,它工作得相当好,但我的同事表示担心作用域声明的类方法与类中的字段同名,例如:
scope :some_field, -> f { where some_field: f }
我的课看起来像
class Foo
....
attribute :some_field
....
我也考虑过.where
通过一个大的 switch 语句来构建一个“链”子句,但这看起来很难看。
tl;博士
是否有基于 Rails 中的查询参数过滤记录的模式和/或最佳实践?
我的最终解决方案
在阅读了 给出的答案Andrew Wei
并花更多时间解决问题后,我决定responds_to
在类本身上使用参数循环,如下所示:
params.each do |params,value|
@mymodels = MyModel.send "by_#{filter}", value, @mymodels if MyModel.respond_to? "by_#{filter}" and not value.blank?
end
其中每个 MyModel 类方法看起来像:
def self.by_some_field(value, relation)
relation.where some_field: value
end