Smart_listing Gem排序

时间:2016-04-05 22:56:57

标签: ruby-on-rails ruby rubygems smart-listing

我将Smart_listing gem整合到我的Rails App上。我的数据库中有 啤酒表 以及 beer_type 列。现在我试图建立一个排序功能,用户可以过滤不同类型的啤酒。与此功能类似example

现在它将完美地过滤每种类型的啤酒。但是,如果检查的啤酒类型超过1种,则不会同时显示啤酒类型。

  

product.rb

scope :with_beer_type_ales, -> (product) { where('beer_type ILIKE?', "%ales%") }
scope :with_beer_type_cream, -> (product) { where('beer_type ILIKE?', "%cream%") }
scope :like, ->(args) { where("name ILIKE? OR beer_type ILIKE? OR description ILIKE?", "%#{args}%", "%#{args}%", "%#{args}%")}
  

products_controller.rb

def index
 products_scope = Product.all
 # Make users initally sorted by name ascending
 products_scope = products_scope.like(params[:filter]) if params[:filter]


 products_scope=products_scope.with_beer_type_ales(params[:with_beer_type_ales]) if params[:with_beer_type_ales] == "1"
products_scope = products_scope.with_beer_type_cream(params[:with_beer_type_cream]) if  params[:with_beer_type_cream] == "1"

 @products = smart_listing_create :products, 
                       products_scope, 
                       partial: "products/list",
                       page_sizes: [10, 20, 30], 
                       default_sort: {name: "asc"}
end
  

index.html.erb

<%= smart_listing_controls_for(:products, {class: "form-inline text-left"}) do %>
     <div class="form-group filter input-append" id="search">
        <%= text_field_tag :filter, '', class: "search form-control",  
          placeholder: "Search...", autocomplete: :off %>
          <button class="btn btn-primary disabled" type="<%= :submit %>">
            <span class="glyphicon glyphicon-search"></span>
          </button>
      </div>

        <h4>Sort By Type:</h4>
        <ul>
            <li class="checkbox">
                <label class="checkbox inline">
              <%= hidden_field_tag :with_beer_type_ales, "0" %>
              <%= check_box_tag :with_beer_type_ales %> Ales
            </label>
            </li>
            <li>
                <label class="checkbox inline">
                <%= hidden_field_tag :with_beer_type_cream, "0" %>
              <%= check_box_tag :with_beer_type_cream %> Cream
            </label>
            </li>
        </ul>
    </div>
<% end %>

1 个答案:

答案 0 :(得分:0)

你想要OR而不是AND。在链中指定多个where子句时,rails默认为AND。

q = Beer.where(true)
q = q.or.where('beer_type ILIKE?', "%ales%")  if params[:with_beer_type_ales] == "1"
q = q.or.where('beer_type ILIKE?', "%cream%") if params[:with_beer_type_cream] == "1"