Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

How to implement live search on a form field.

I am building a business app and I have a form with a few fields:

user_id friend_id - Search db based on what is entered here. title project_cat etc

I would like to search the users friends to suggest them to when they are filling out the form. I have found tutorials online. Mainly this one http://railscasts.com/episodes/240-search-sort-paginate-with-ajax.

But this is a dedicated search form, I want to be able to search a db table via ajax only without a form.

Any suggestions much appreciated, I may even write a blog article for others because I cant find the right info for my scenario. If you need more details just ask :)

So are you using the search to just find a friend of a user and then the form is to create something else?

Or do you just want search results of the user's friends?

The first point you made. "So are you using the search to just find a friend of a user and then the form is to create something else?"

1 Answer

Awesome then this is fairly easy to implement using select2.js. Select2 turns an ordinary select field into a searchable input field. It looks really nice and makes it easier to find a friend then searching all the options in the select field.

So in your controller, you will want to have an instance variable

@friends = @user.friends

Then in your _form.html.erb view,

<%= f.label :friend %>
<%= f.select :friend_id, options_for_select(@friends.collect{ |f| [f.id, f.first_name] }, @model.friend), { include_blank: true }, { id: "add-friend-select" } %>

Then in your js file:

$(document).ready(function(){
    $("#add-friend-select").select2();
});

This code will probably not work immediately and will need some tweaking, but it's a start. Don't hesitate to ask if you have any questions.

Not exactly what I require becuase I really would like friends to be loaded in via ajax because if someone has 1000 friends or more it will slow down the application. With AJAX I can limit the return to the top ten matches for example. However it does provide some functionality that I can investigate and learn from. If you have any other suggestions based on what I have put then please add more. Thanks again!