Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query DB for first or last name

I’m working on a search feature for my users table so that I can query a user and display it in my app. So far I have it working for first_name but I’m unsure of the syntax to use to also search last name in the same query. My users controller looks like this:

  def search
   if params[:search].blank?
    redirect_to users_path and return
  else
   @parameter = params[:search].downcase
   @results = User.all.where("lower(first_name) LIKE :search", search: "%#{@parameter}%")
 end
end

Output:

User Load (0.9ms)  SELECT "users".* FROM "users" WHERE (lower(first_name) LIKE '%laura%')

My search form looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="input-group">
    <%= search_field_tag :search, params[:search], placeholder: "Type ", class: "form-control" %>
        <div class="input-group-btn">
            <%= button_tag "Search User", class: "btn btn-info", :name => nil %>
        </div>
    </div>
<% end %>

And my results page:

<% @results.each do |result| %>
  <tbody>
     <tr>
       <td><%= link_to result.full_name, user_path(result) %></td>
       <td><%= result.email %></td>
       <td><% if result.subscribed? %>
       <span class="badge rounded-pill bg-success">Subscribed</span>
         <% else %>
       <span class="badge rounded-pill bg-danger">Not Subscribed</span>
     <% end %>

This works perfect however I’d like to be able to put a last_name and display those results.
I know I’m close but a few things I’ve tried has not worked.

Thanks!

>Solution :

Did you try changing

@results = User.all.where("lower(first_name) LIKE :search", search: "%#{@parameter}%")

into

@results = User.all.where("lower(first_name) LIKE :search or lower(last_name) LIKE :search", search: "%#{@parameter}%")

Please do and update…

R

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading