1

我正在寻找基于任意数量的查询参数过滤返回到 Rails 视图的记录的最佳方法,例如:

http://localhost:3000/foo?some_field=fubar&this_field_left_blank=&a_third_field=bar

我目前在做什么

我找到并使用了has_scopegem,它工作得相当好,但我的同事表示担心作用域声明的类方法与类中的字段同名,例如:

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
4

1 回答 1

2

这是我通常做的。我并不是说这是“Rails 方式”。

where = {}

if params[:one]
    where["one"] = params[:one]
end

if params[:two] # .empty? , .nil?, x > 0... etc
    where["two"] = params[:two].to_i
end

@somethings = Something.where(where)

显然,您将保护变量的分配方式。我只是想展示我使用的模式。

于 2013-10-30T01:32:50.783 回答