Search code examples
ruby-on-railsruby-on-rails-4ransack

How use ransack


good? In one more test, wanna learn ransack, but I'm in a point that I say WTF, take look image please:

It's a problem

Is all repeat, I know wHy, I put Product.all in index.html.erb:

<%= search_form_for @q do |f| %>

  <%= f.label :name_cont, "Name" %>

  <br />

  <%= f.search_field :name_cont %>

  <br />

  <%= f.label :hd, "Brand" %>

  <br />

  <%= f.collection_check_boxes :brand, Product.all, :brand, :brand %>

  <br />

  <%= f.label :hd, "HD" %>

  <br />

  <%= f.collection_check_boxes :hd, Product.all, :hd, :hd %>

  (...)

  <%= f.submit "Search" %>

<% end %>

In controller have just this:

def index
  @q = Product.ransack(params[:q])
  @products = @q.result
end

The uniq_value don't work, is error. I wanna that on click in search show just one value... for example, have 2 500 HD's notebooks registered, wanna show just a checkbox with value 500gb and on click, show both notebooks, understand? Thanks !


Solution

  • a cheap and dirty way to accomplish this is to use a distinct select on the particular fields, i.e:

    <%= f.collection_check_boxes :brand, Product.select(:brand).distinct, :brand, :brand %>
    

    and

    <%= f.collection_check_boxes :hd, Product.select(:hd).distinct, :hd, :hd %>
    

    This results in an SQL Query like SELECT DISTINCT brand FROM products.

    A cleaner way, if possible, is to normalize your database and create a model called Brands and link the products with brands i.e a product belongs to a brand.