Search code examples
ruby-on-railsransack

How to construct a clickable link with a scope using Ransack and Rails


I have the requirement to have some scopes as clickable links in my application. This will allow the user to change the data they are seeing as required. Using Ransack and it's ransackable_scopes functionality I am very close. I do need to retain any filtering Ransack has done when the user clicks the scope.

I've got the scopes working but now I just need to construct the clickable link.

Here's my model:

class Product < ActiveRecord::Base    

    scope :upward_trending, -> { where( "status > ?", 100).where(above_revenue_average: true).order('end_date DESC') }
scope :downward_trending, -> { where( "status < ?", 100).order('end_date DESC') }

    def self.ransackable_scopes(auth_object = nil)
    [:upward_trending, :downward_trending]
    end
end

Now in my view I've added these two scopes as hidden fields, like so:

        <%= search_form_for @q, :html => {:class => 'filter-form'} do |f| %>

        <div>

            <%= f.hidden_field :upward_trending %>
            <%= f.hidden_field :downward_trending %>

            <%= f.label :name_cont, "Search", class: 'label' %>
            <%= f.search_field :name_cont, class: 'form-control input-box', :placeholder => 'Search' %>

        </div>

        <div>

            <%= f.submit "Filter", class: 'btn btn-primary' %>
            <%= link_to "Clear Search", request.path, class:"btn btn-default" %>

        </div>
        <% end %>

From here I just need to create the links and it should work.. What is the best way to do this?

Thanks for your help!


Solution

  • I achieved this by creating hidden fields for each scope and then creating a button with onclick javascript:

    <%= f.hidden_field :upward_trending %>
    
    <%= button_tag(:type => 'submit', :class => 'btn btn-primary scope-button upward_trending', :id => "upward_trending", :onclick => "document.getElementById('q_downward_trending').value = 0; document.getElementById('q_upward_trending').value = 1;") do %>
        <i class="fa fa-chevron-up fa-2x"></i><br>Upward<br>Trending
        <% end %>