ahk
ahk

Reputation: 17

rails 4 simple search form for users to find each other

I am trying to implement simple search form for users to look up other users.. I have been looking around the web for quite some time, but lot of the resources seem to be outdated, either for rails 3 or retired gems...

Can anyone pin point me to a recent rails 4 resources for simple search or show me the skeleton code to start? thank you in advance!

Upvotes: 0

Views: 1664

Answers (2)

Bad Wolf
Bad Wolf

Reputation: 81

For a very simple search on Users username you can do in your view :

<%= form_tag users_path, :method => 'get', :id => 'users_search' do %>
    <p>
        <%= text_field_tag :search, params[:search] %>
        <%= submit_tag "Search", :name => nil %>
    </p>
<% end %>

In your User model you must define a 'search' method :

#users_controller.rb
def self.search(user_name)
    if user_name
        user_name.downcase!
        where('LOWER(name) LIKE ?', "%#{user_name}%")
    else
        all
    end
end

and finally in your controller you can call this method :

def index
    @users = User.search(params[:search])
end

The route can be defined as a GET like your default route for the page :

#routes.rb
resources :users

Upvotes: 1

Vlad
Vlad

Reputation: 901

https://github.com/jhund/filterrific

scope :search_query, lambda { |query|
  return nil if query.blank?

  terms = query.to_s.downcase.split(/\s+/)

  # replace "*" with "%" for wildcard searches,
  # append '%', remove duplicate '%'s
  terms = terms.map { |e|
    (e.gsub('*', '%') + '%').gsub(/%+/, '%')
  }

  # configure number of OR conditions for provision
  # of interpolation arguments. Adjust this if you
  # change the number of OR conditions.
  num_or_conds = 2
  sql = "(LOWER(foo.first_name) LIKE ? OR LOWER(foo.last_name LIKE ?)"

  where(
    terms.map { |term| sql }.join(' AND '), *terms.map { |e| [e] * num_or_conds }.flatten
  )
}

That would be a simple example of searching a user by either first_name or last_name. Filterrific is quite good, but can be heavy on the back side when it does the query if you have many records.

Upvotes: 1

Related Questions