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

How to use has_scope gem in a view in rails 4?


I'm trying to add a clickable link that will sort a page of links alphabetically using has_scope gem. What exactly would i put in my view to make this work?

Model Links.rb

 scope :abc, -> { order("links.title ASC") }


Links_Controller.rb

 has_scope :abc

 def index
    @links = apply_scopes(Link).all
 end


Index.html.erb

<div id="links-wrapper">
    <%= render partial: "shared/link", collection: @links %>
</div>


_link.html.erb

<div class="link">

    <a class="link-title" href="<%= link.url %>" target="_blank"><%= link.title %></a>


    <div class="link-printed-url"><%= link.url %></div>

    <p class="link-description"><%= link.description %></p>

    <div class="link-tags">
        <% link.tags.any? %>
            <% link.tags.each do |tag| %>
                <span class="label-tag">
                    <%= link_to tag_path(tag) do %>
                        #<%= tag.name %>
                    <% end %>
                </span>     
        <% end %>
    </div>


</div>

Solution

  • You need to pass a title param to the scope.

    Change the scope in the model to scope :abc, -> title { order("links.title ASC") }

    or

    scope :abc, -> title { order(title: :asc) }

    You could do something like this in the partial

      <div class="link">
        <a class="link-title" href="<%= link.url %>" target="_blank"><%= link.title %></a>
    
    
        <div class="link-printed-url"><%= link.url %></div>
    
        <p class="link-description"><%= link.description %></p>
    
      </div>
      <% end %>
    
      <div class="link-tags">
        <%= link_to 'Order ASC', tag_path(:abc => true) %>
      </div>