0

I want to include a search functionality to my rails app. I have included a search by date that works just fine, however the search by name LIKE ? isn't giving me any results.

I would like the name search to be a wildcard search.

Can anyone please tell me where I might be going wrong?

View for index.html.erb:

<%= form_tag(appointments_path, :method => "get") do %>
  <%= text_field_tag :search, nil, :placeholder => "Search Full Name" %>
  <%= text_field_tag :search, nil, :placeholder => "Search Date (YYYY-MM-DD)"%>
  <%= submit_tag "Search" %> 
<% end %>

Controller:

def self.search(search_for)
  Appointment.where('name Like ?', search_for)
  Appointment.where('date = ?', search_for)
end
Tom Lord
  • 27,404
  • 4
  • 50
  • 77
OkiGirl
  • 45
  • 7

1 Answers1

1

In SQL, I think your query ought to be:

def self.search(search_for)
    Appointment.where('name LIKE ?', "%#{search_for}%")
end

On another note, I think the problem you might be encountering is that your form only sends a search parameter. Meaning when you set the name, immediately after the date is overriding it.

A way to approach this might be to change the names of the input field, like so:

<%= form_tag(appointments_path, :method => "get") do %>
  <%= text_field_tag :search_name, params[:search_name], :placeholder => "Search Full Name" %>
  <%=text_field_tag :search_date, params[:search_date], :placeholder => "Search Date (YYYY-MM-DD)"%>
  <%= submit_tag "Search" %> 
<% end %>

In your controller, you could do:

def search
  Appointment.search(search_params)
end

private
  def search_params
    params.permit(:search_date, :search_name)
  end

In your appointment model, you could have:

def self.search(search_date, search_name)
    Appointment.where("name LIKE :search_name OR date = :search_date", search_name: "%#{search_name}%", search_date: search_date)
end
Sam Coles
  • 4,003
  • 24
  • 19
oreoluwa
  • 5,553
  • 2
  • 20
  • 27
  • Thank you very much for your response!You are right, it the date is overriding the name search. However I tried to implement your suggestion to fix it, but it's not giving any search results for either. – OkiGirl Jul 21 '16 at 22:41
  • @OkiGirl Are you sure that there's data matching your search? Please double check. – MarsAtomic Jul 21 '16 at 22:58
  • Try this again with the updated search method: def self.search(search_date, search_name) – Sam Coles Jul 22 '16 at 01:00