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:
<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!
CodePudding user response:
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
CodePudding user response:
On Postgres you can use ILIKE
to perform a case insensive match:
def search
@term = params[:search]
redirect_to users_path and return unless @term.present?
@users = User.where(
'users.first_name ILIKE :term OR users.last_name ILIKE :term',
term: "%#{@term}%"
)
end