【问题标题】:Can I query the current scope(s)?我可以查询当前范围吗?
【发布时间】:2014-06-26 15:36:34
【问题描述】:

我的集合模型有这样的范围

scope :got, -> { where(status: 'Got') }

我有一个指向如下索引的链接

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

感谢 has_scope gem,它创建了用户集合的索引,其中 status: 是 'Got'。路径是

users/user1/collections?got=true

在那个索引视图中,我希望能够编写类似

的内容
<% if status: 'Got' %>
   You have these ones
<% end %>

但无论我如何编写它,我似乎都无法查询链接中传递的范围。有这样做的标准方法吗?

【问题讨论】:

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


    【解决方案1】:

    你可以这样做:

    <% if params[:got].to_s == 'true' %>
       You have these ones
    <% end %>
    

    但这会迫使您使用true 作为params[:got] 的值。也许这样更好:

    <% if params[:got].present? %>
       You have these ones
    <% end %>
    

    但这将适用于以下参数:

    • users/user1/collections?got=true,
    • users/user1/collections?got=false,
    • users/user1/collections?got=NOPE,

    实际上,has_scope gem 提供了一个方法current_scopes,它在相应的视图中返回一个哈希(键 = 范围,值 = 赋予范围的值)。你应该可以这样做:

    <% if current_scopes[:got].present? %>
       You have these ones
    <% end %>
    

    【讨论】:

    • 太好了。我没有意识到范围在通过时变成了参数,但这完全有道理。 current_scopes 方法作为代码是否更好?两者都是一种享受。非常感谢。
    • current_scopes 方法更适合您的情况。它只是类的@current_scopes 实例变量的getter,包括模块HasScope (has_scope/lib/has_scope.rb:182)
    • 太棒了。那就用那个。现在我需要确定是否可以在索引页面的搜索表单中传递这些范围。虽然还不能写另一个问题。非常感谢。
    • 在这里添加了新问题 :) stackoverflow.com/questions/24436568/…
    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多