将 current_scopes 传递给搜索 [英] Pass current_scopes on to search

查看:89
本文介绍了将 current_scopes 传递给搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用非常有用的 has_scope gem.我有一个通过在链接中传递范围创建的索引页.

I'm using the very helpful has_scope gem. I have an index page created by passing scopes in a link.

<%= user_collections_path(@user, got: true) %>

在该索引页上,我可以查询 current_scopes.

On that index page I can query the current_scopes.

我在该页面上有一个非常标准的搜索表单,但使用它返回的结果没有任何范围.

I have a pretty standard ransack search form on that page but using it returns results without any scopes.

如何将 current_scopes 传递给搜索?我尝试使用隐藏字段,但无法使其正常工作.我想如果我可以在链接中传递范围,我应该能够以表单的形式传递它们,但在谷歌搜索后我不确定这是真的.

How can I pass the current_scopes on to the search? I tried using a hidden field but couldn't get it to work. I thought if I could pass the scopes in a link I ought to be able to pass them in a form but after googling I'm not sure that is true.

搜索表单

<%= search_form_for @search, :html => {:method => :post} do |f| %>
    <%= f.text_field :name_or_miniature_name_cont, class: "span3" %>
    <%= f.submit "Search", class: "btn" %>
<% end %>

索引方法

 def index
    @user = User.find_by_username(params[:user_id])
    @search = apply_scopes(@user.collections).search(params[:q])
    @search.sorts = 'created_at desc' if @search.sorts.empty?  
    @collections = @search.result.paginate(page: params[:page])
 end

推荐答案

使用 Ransack 1.6+ 中的新功能,您可以将范围引入到 Ransack 搜索中,但首先您需要将它们列入白名单,如下所示:

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 })

您也可以照常将它们添加到您的 search_form_for 中.

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

我希望这会有所帮助.

这篇关于将 current_scopes 传递给搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆