【问题标题】:Pass current_scopes on to search将 current_scopes 传递给搜索
【发布时间】:2014-06-26 17:16:20
【问题描述】:

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

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

在那个索引页面上,我可以查询 current_scopes。

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

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

搜索表单

<%= 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

【问题讨论】:

  • 嘿@Ossie 你解决过这个问题吗?我现在也有同样的要求
  • 不高兴。令人沮丧。
  • 嘿伙计遇到了同样的问题,并且已经能够使用新的 Ransack 功能解决它,检查我的答案,如果有帮助,请告诉我。
  • 我现在无法测试,但我会的,谢谢!

标签: ruby-on-rails ruby-on-rails-4 named-scope has-scope


【解决方案1】:

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

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

然后你可以像这样触发它们:

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

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

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

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您可以从当前session 存储/检索数据,而不是将其放入 url 参数中。

    引用an issue的评论:

    这就是 has_scope 支持 :default 的原因,所以你可以给一个 proc a 从会话中检索值:

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

    【讨论】:

    • 好的。听起来不错。不太确定如何实现。什么时候会从会话中删除范围?有点担心范围堆积。
    • @WorldOfProper 直到您覆盖该值或它过期。
    【解决方案3】:

    您可以在操作 url 中传递当前范围:

    <%= search_form_for @search, url: search_people_path(current_scopes), do |f| %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-20
      • 2015-12-28
      • 2019-12-12
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 2012-04-04
      • 2019-11-11
      相关资源
      最近更新 更多