ruby-on-railsruby-on-rails-5pg-search

Print pg_search params to Rails 5 template page


I have a products page that is filterable with pg_search gem. What I would like to do is create a breadcrumb that lists the search params onto the page.

If my search url looks like http://127.0.0.1:3000/products?utf8=%E2%9C%93&query=modern&query=stone&query=limestone&commit=Search I would like to print modern stone limestone to the page.

products_controller.rb

def index
  @products = if params[:query]
               @albums = Album.where(name: params[:query])
               Product.search_for(params[:query])
              else
               @albums = Album.where(name: 'products')
                 Product.order(:name)
               end
end

index.html.erb This is what I tried, but realized that it lists ALL the tags, which I only need the tags that are part of the search params

<ul class="product-index-breadcrumb">
  <% @products.each do |p| %>
    <% p.tags.each do |t| %>
      <li><%= t.name %></li>
    <% end %>
  <% end %>
</ul>

Solution

  • You need to modify your URL e.g array string adding [] if you keep this then it only without [] then it takes only last value like limestone, after modification URL then it will look like this http://http://127.0.0.1:3000/products?utf8=%E2%9C%93&query[]=modern&query[]=stone&query[]=limestone

    then if you write like

    <%= params[:query] %>
    

    it will return

    ["modern", "stone", "limestone"]
    

    now you can run a loop like

    <ul>
        <% params[:query].each do |query_params|  %>
            <li><%= query_params %></li>
        <% end  %>
    </ul>
    

    then output is