Use*_*012 1 ruby ruby-on-rails-3 ransack
我正在使用ransack根据用户的公司和活动/非活动参数来搜索用户。单独使用时效果很好,但我想同时使用两者。例如,如果我首先选择公司,然后选择活动/非活动用户,则公司名称应该保留。
其次,当我返回或再次点击用户时,ransack 中是否有一个工具可以保留这两个值?
更新 :
这是我的观点:
= search_form_for @search, url: search_users_path, method: :post, html: { class: 'sort' } do |f|
= f.label 'company:'
= f.select :company_id_eq,
Company.where('is_inactive = false').collect {|c| [ c.name, c.id ] },
{:include_blank => 'All company users'}, :'data-remote' => true, class: 'searchSelect searchUserSelect'
%div.sort_users
= f.label 'sort Users:'
= f.select :deleted_eq,
[raw("<option value= 0 selected=#{session[:deleted]}>Active Users</option><option value= 1>Inactive Users</option>")],
{}, :'data-remote' => true, class: 'searchSelect searchUserSelect', style: "width: 205px;"
Run Code Online (Sandbox Code Playgroud)
这是我在控制器中的代码
@search = User.search(params[:q])
@users = @search.result.includes(:company).order("companies.name, last_name").page(params[:page]).per(20)
Run Code Online (Sandbox Code Playgroud)
before_action
关于过滤器持久性,我在中使用以下内容ApplicationController
:
def get_query(cookie_key)
cookies.delete(cookie_key) if params[:clear]
cookies[cookie_key] = params[:q].to_json if params[:q]
@query = params[:q].presence || JSON.load(cookies[cookie_key])
end
Run Code Online (Sandbox Code Playgroud)
然后,对于一个Intervention
模型,我有以下内容:
class InterventionsController < ApplicationController
before_action only: [:index] do
get_query('query_interventions')
end
def index
@q = Intervention.search(@query)
@interventions = @q.result
end
end
Run Code Online (Sandbox Code Playgroud)
这样,如果在interventions_path
没有参数的情况下调用q
,cookies['query_interventions']
则检查是否访问最后一个持久查询。但是,当interventions_path
使用q
参数调用时,将使用这个新查询并保留以供以后使用。
另外,如果interventions_path
使用clear
参数调用,则 cookie 会被删除。
CookieOverflow
请注意,如果存储超过 4k,则会引发异常,但这是在1024 到 4096 个 UTF-8 字符之间,通常没问题。如果没有,您应该使用其他类型的会话存储。