简体   繁体   中英

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>

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>

由于has_scope使用url params,你需要在link_to上添加params

<%= link_to "title", links_path(abc: true) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM