Paramètres de routage Paramètres du contrôleur afficher le fichier: créer une recherche
Ajout de la recherche au routage des profils.
rutes.rb
resources :profiles do
get :search, on: :collection
end
search_profiles GET /profiles/search(.:format) profiles#search
Cette fois, nous supposons un cas où il y a une correspondance partielle pour: nom, un cas où le sexe correspond, ou un cas où les deux correspondent.
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?
#Match partiel
@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>Barre de recherche</h1>
<%= form_with url: search_profiles_path, method: :get, local: true do |f| %>
<%= f.label :name, "Nom" %>
<%= f.text_field :name %>
<%= f.label :Masculin%><%= f.radio_button :sex, :Masculin%>
<%= f.label :Femme%><%= f.radio_button :sex, :Femme%>
<%= f.submit :search %>
<% end %>
Recommended Posts