Rails:将可选参数组合到查询中

我有一个视图,其中包含需要过滤的大量分页记录列表。

用户可以通过几种不同的方式过滤记录(例如“已保存”记录,“读取”记录和“标记已删除”记录),我希望他们能够以任何可能的方式组合这些filter。

我目前的,有缺陷的,无法运作的方法。 除非所有参数都被指定且有效,否则下面的代码不会生成任何内容:

#view. Set the 'se' filter to true; leave all others as is params[:id], :se=>"true", :st=>params[:st], :re=>params[:re]) do %> 
Toggle SE
#controller query. Add whichever params are passed into the conditions for the new page. #query is paginated and sorted @records = Record.where("user_id IN (?) AND see = ? AND star = ? AND delete = ? AND like = ?", @users.select("id"), params[:se], params[:st], params[:re]).paginate :page => params[:page], :order => (sort_column + " " + sort_direction)

创建此过滤系统的最佳方法是什么?
我想客户端排序比要求服务器每次都参与更快 – 是否有简单的AJAX方法来完成这种事情? 想象filter,用户可以任意组合打开和关闭

试试这个:

 conditions = {:user_id => @users.select("id")} { :se => :see, :st => :star, :del => :delete }.each{|k1, k2| conditions[k2] = params[k1] unless params[k1].blank?} @records = Record.where(conditions).paginate(...) 

conditions哈希将根据params哈希中存在的值填充。

编辑1

您可以组合条件哈希和数组。

 @records = Record.where(conditions).where( ":created_at > ?", Date.today - 30).paginate(...) 

您可以通过指定将user_id条件更改为您想要的任何内容

 conditions[:user_id] = @user.id 

在上面的语句中,如果RHS是一个数组,rails会自动生成IN子句。 否则,执行等式检查( = )。

也可以使用匿名范围: 在Rails中组合条件数组