Pass current_scopes on to search

时光毁灭记忆、已成空白 提交于 2019-12-06 15:41:59

Using the new functionality in Ransack 1.6+ you can introduce scopes into your Ransack search, but first you need to whitelist them, like so:

class Employee < ActiveRecord::Base
  scope :active, ->(boolean = true) { where(active: boolean) }
  scope :salary_gt, ->(amount) { where('salary > ?', amount) }

      # `ransackable_scopes` by default returns an empty array
      # i.e. no class methods/scopes are authorized.
      # For overriding with a whitelist array of *symbols*.
      #
   def self.ransackable_scopes(auth_object = nil)
    [:active, :salary_gt]
   end
end

Then you can trigger them like this:

Employee.ransack({ active: true, hired_since: '2013-01-01' })

Employee.ransack({ salary_gt: 100_000 }, { auth_object: current_user })

You can also add them to your search_form_for as per normal.

I hope this helps.

You could store / retrieve the data from the current session rather than to put it into a url parameter.

To quote a comment on an issue:

This is the reason has_scope supports :default, so you can give a proc a retrieve the value from session:

has_scope :degree, :default => proc { |c| c.session[:some_value] }

You could pass current scopes in the action url:

<%= search_form_for @search, url: search_people_path(current_scopes), do |f| %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!