Routing settings Controller settings view file: create search
Added search to profiles routing.
rutes.rb
resources :profiles do
get :search, on: :collection
end
search_profiles GET /profiles/search(.:format) profiles#search
This time, we assume a case where there is a partial match for: name, a case where the gender matches, or a case where both match.
controller.rb
def search
if params[:name].present? && params[:sex].present?
@profiles = Profile.where('name LIKE ?', "%#{params[:name]}%").where(sex: "#{params[:sex]}")
elsif params[:name].present?
#Partial Match
@profiles = Profile.where('name LIKE ?', "%#{params[:name]}%")
elsif params[:sex].present?
@profiles = Profile.where(sex: "#{params[:sex]}")
else
# @profiles = Profile.none
@profiles = Profile.none
end
end
search.html.erb
<h1>Search box</h1>
<%= form_with url: search_profiles_path, method: :get, local: true do |f| %>
<%= f.label :name, "name" %>
<%= f.text_field :name %>
<%= f.label :male%><%= f.radio_button :sex, :male%>
<%= f.label :Female%><%= f.radio_button :sex, :Female%>
<%= f.submit :search %>
<% end %>
Recommended Posts