1

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?

Ossie
  • 1,103
  • 2
  • 13
  • 31

1 Answers1

1

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 %>
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • That's great. I didn't realise the scope became a param when passed but that makes total sense. Is the current_scopes method any better as code? Both work a treat. Thank you so much. – Ossie Jun 26 '14 at 15:50
  • 1
    The `current_scopes` method is better in your case. It is just a getter of the `@current_scopes` instance variable of the class including the module `HasScope` (`has_scope/lib/has_scope.rb:182`) – MrYoshiji Jun 26 '14 at 15:56
  • Great. Using that then. Now I need to work out if I can pass those scopes on in the search form on the index page. Can't write another question yet though. THanks so so much. – Ossie Jun 26 '14 at 16:06
  • Added new question here :) http://stackoverflow.com/questions/24436568/pass-current-scopes-on-to-search – Ossie Jun 26 '14 at 17:18