Search code examples
ruby-on-railsruby-on-rails-4named-scope

Can I query the current scope(s)?


My collections model has a scope like this

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

I have a link to an index as follows

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

Thanks to the has_scope gem that creates an index of the user's collections where the status: is 'Got'. the path is

users/user1/collections?got=true

In that index view I want to be able to write something like

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

But no matter how I write it I can't seem to query the scope that was passed in the link. Is there a standard way of doing this?


Solution

  • You can do as following:

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

    But this forces you to use true as value for params[:got]. Maybe this is better:

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

    But this will work with params like:

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

    Actually, the has_scope gem provides a method current_scopes that returns a hash (key = scope, value = value given to the scope) in the corresponding views. You should be able to do like this:

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