Home > Mobile >  Making dynamic search form to stop bloating Controller
Making dynamic search form to stop bloating Controller

Time:11-02

I have a search form with 2 ways of searching records, name and email.

  <%= form_tag(clients_path, method: :get, class: "d-flex") do %>
    <%= text_field_tag(:client_name, params[:client_name], placeholder: "Buscar por nombre", class: "form-control") %>
    <%= text_field_tag(:client_email, params[:client_email], placeholder: "Buscar por email", class: "form-control") %>
    <%= submit_tag ("Buscar"), class: "btn btn-primary" %>
  <% end %>

In my controller

if params[:client_name]
  @clients = User.where(name: params[:name])
else
  @clients = User.all
end
if params[:client_email]
  @clients = User.where(email: params[:client_email])
else
  @clients = User.all
end

This works only when searching for 1 condition.

How can I make my controller code dynamic and check if any of conditions are made, show the corresponding results in my @clients variable? I don't want to bloat my controller...

Thanks!

CodePudding user response:

I would change it to:

@clients = User.all
@clients = @clients.where(name: params[:name]) if params[:name]
@clients = @clients.where(email: params[:client_email]) if params[:client_email]
  • Related