0

I am trying to make a search bar in order to find some cocktails by their name in my index. All I got is an empty array... I believe my SQl request is not good... I'd need help please to make it working. Regards

Here is my code:

Search form:

  <%= simple_form_for :query,  url: cocktails_path, :method => :get do |f| %>
       <%= f.input :search %>
       <%= f.button :submit %>
   <% end %>

cocktails controller:

 def index
    if params[:query].present?
      @cocktails = Cocktail.all
      @cocktail_search = @cocktails.where('cocktails.name LIKE ?', params[:query][:search])
      binding.pry
    else
      @cocktails = Cocktail.all
    end
  end

the index view:

<% if @cocktail_search %>
    <% @cocktail_search.each do |cocktail| %>
     <div class="col-xs-12 col-sm-3">
        <div class="card"  style="background-image: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.2)),
           url('<%= cl_image_path cocktail.photo %>');">

           <h2 class="card-description"><%= link_to cocktail.name, cocktail_path(cocktail)%></h2>
        </div>
      </div>
    <% end %>
  <% else %>
    <% @cocktails.each do |cocktail| %>
      <div class="col-xs-12 col-sm-3">
        <div class="card"  style="background-image: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.2)),
           url('<%= cl_image_path cocktail.photo %>');">

           <h2 class="card-description"><%= link_to cocktail.name, cocktail_path(cocktail)%></h2>
        </div>
      </div>
    <% end %>
  <% end %>

This is my binding pry

2 Answers2

0

@cocktail_search = @cocktails.where('cocktails.name LIKE ?', params[:query][:search])

If your table has column "name", then:

@cocktail_search = @cocktails.where('name LIKE ?', params[:query][:search])

should do the work.

When you're uncertain about what is wrong you can rails console and check things yourself, ex. Coctail.where("name like ?", "Mojito") and see if it returns expected result.

Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18
0

Since you use LIKE it seems like you want to find cocktails every if the search term matches only parts of the name. This can be archived by using % (see: Safe ActiveRecord like query).

Furthermore you might want to use a case-insensitive ILIKE instead of LIKE:

@cocktails.where('name ILIKE ?', "%#{params[:query][:search]}%")

Without the % you query is basically the same as

@cocktails.where(name: params[:query][:search])

that only returns exact matches.

Community
  • 1
  • 1
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Super ! I was also trying this but forgot to use double quotes for the interpolation... Thanks for this :) –  Feb 18 '17 at 22:45