Rails:将可选参数组合到查询中 [英] Rails: combining optional params into a query
问题描述
我有一个包含大量需要过滤的记录的分页列表的视图.
I have a view with a huge paginated list of records that need filtering.
用户可以通过几种不同的方式(例如保存"记录、读取"记录和标记已删除"记录)按记录过滤,我希望他们能够组合 这些过滤器以任何可能的方式进行.
Users can filter by records a few different ways (such as 'saved' records, 'read' records, and 'mark deleted' records) and I'd like for them to be able to combine these filters any possible way.
我目前的、有缺陷的、不起作用的方法.除非所有参数都已指定且有效,否则下面的代码不会产生任何结果:
My current, flawed, non-functioning approach. The code below does not produce anything unless all of the params are specified and valid:
#view. Set the 'se' filter to true; leave all others as is
<%= link_to list_url(:id=>params[:id], :se=>"true", :st=>params[:st], :re=>params[:re]) do %>
<div class="button">Toggle SE</div>
<% end %>
#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 方法来完成这种事情?想象一下,用户可以以任意组合打开和关闭过滤器.
What is the best way to create this filtering system?
I imagine a client-side sort would be faster than asking the server to become involved every time - is there a simple AJAX way to accomplish this kind of thing? Imagine filters the user can toggle on and off in any combination.
推荐答案
试试这个:
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
哈希中存在的值填充.
The conditions
hash will be filled based on the values present in the params
hash.
编辑 1
您可以组合条件散列和数组.
You can combine conditions hash and array.
@records = Record.where(conditions).where(
":created_at > ?", Date.today - 30).paginate(...)
您可以通过指定
conditions[:user_id] = @user.id
在上面的语句中,如果RHS是一个数组,rails会自动生成IN
子句.否则,执行相等检查(=
).
In the above statement, if the RHS is an array, rails automatically generates the IN
clause. Otherwise, equality check(=
) is performed.
这篇关于Rails:将可选参数组合到查询中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!