Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Derek Saunders
Derek Saunders
5,167 Points

Adding a search field

Would it be possible to add a search box where you could type like soccer, books, music, etc. to then generate a list of users that have the same interest? If so how would you go about doing this?

1 Answer

For this specific example it could be achieved fairly easily by first adding a search field to your view that points to a search action in the users controller:

  <%= form_for :search, url: search_users_path do |form| %>
    <%= form.text_field :query %>
  <% end %>

Add a route for the actions:

  resources :users do
    collection do
      post :search

Then adding an action to the users controller that searches users by interest (assuming Interest has a field "name":

  def search
    @users = User.include(:interests)
                    .where('interests.name LIKE ?', "%#{params[:search][:query]%")
    render :index

This will do a partial text search of interest names submitted from the form and return all of the users which have this interested associated. If you'd like to be able to search for multiple interests at the same time you'll have to get a little fancier I'm afraid. Likewise if you plan on being able to search for users based on multiple fields you'll want to consider some full-text search options instead of writing the queries by hand. There are many options available for full-text search in rails, some of which will require other processes to be running to index the database.

Hopefully this helps for your needs though!