nour nour - 2 months ago 6
Ruby Question

ruby operationin where method

I have this code so what I am trying to do is if I typed the first name or the last name in the search it will result any of first or last

def self.search_by(search_term)
where(["LOWER(first_name) LIKE :search_term",
{search_term: "%#{search_term.downcase}%" } ]
) || where(["LOWER(last_name) LIKE :search_term",
{search_term: "%#{search_term.downcase}%" } ]
end


<%= form_for "", url: members_path, class: "navbar-form navbar-left", role: "search", method: :get do %>
<div id="tfheader">
<%= text_field_tag :search, @search_term ,id: "search",class: "tftextinput", size: "21", maxlength: "120" %>
<input type="submit" value="Search" class="tfbutton">
<div class="tfclear"></div>
</div>
<% end %>


Ex:


  • First_name Last_name

  • John Smeth

  • Salma Hayek



if I type in the text area john it will give me the whole row or if I typed hayek it also give me the whole row

Answer

The logical disjunction should be done in the query, that said, on DB level, not on ruby one:

def self.search_by(search_term)
  where(
    "LOWER(first_name) LIKE :search_term OR LOWER(last_name) LIKE :search_term",
    search_term: "%#{search_term.downcase}%"
  )
end
Comments