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

☆樱花仙子☆ 提交于 2019-12-02 07:01:31

问题


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!


回答1:


I was planning to do dirty way. (But haven't yet)

  • create search_form_for every scope (you will have 2 form for your case)
  • set hidden field with own criteria (as you do in your code but each in own form)
  • make submit button looks like link (with css I think it is not very difficult. You can see Bootstrap button appeared as link)

Not very clean or elegant.




回答2:


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 %>


来源:https://stackoverflow.com/questions/28591645/how-to-construct-a-clickable-link-with-a-scope-using-ransack-and-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!