-
Notifications
You must be signed in to change notification settings - Fork 24
[Appendix] Autocomplete Fields
With the amount of people that we're going to have in our database for sign-ups, it would be a hassle and just very tedious to have to type out emails to grant permissions for organizers/mentors/admins. So... autocomplete to the rescue!
With Rails' beautiful support for all things and the greatness of jquery, 'rails-jquery-autocomplete' was the perfect fit for what I was trying to do.
Messing with the Model was actually unnecessary for this implementation since it only deals with the fields inside the controller, routes, and the end-result showing up in the Views.
In the Pages Controller, all we need to add is
autocomplete :user, :email, :full => true
The user is the table that we're looking for, and the email is the field, and the "full" makes it so that the search will match the email string at any index, and not just the beginning.
Creating this means we need to add a route to our routes.db file so that our view can callback to the controller and look for all the emails and that's just a couple lines of code :
resources :pages do
get :autocomplete_user_email, :on => :collection
Looking good! Now for the final bit of magic, we modify the _permissions.html.erb of Views:
data: {autocomplete: autocomplete_user_email_pages_path}, 'min-length' => 1%
All we need to add that bit to a text_field tag where we type in the emails to grant permissions. The autocomplete aspect is just a reference to the route where it gets all the emails, and the min-length just controls the minimum length for when it starts searching (the default is 2).
Now, without a further ado, let's see that beautiful autocomplete!
....err. Well, so apparently gems can't do everything! I mean come on, it won't even highlight hovered objects. What are we, cavemen?
But not to fret, with a little bit of Googling, jquery doesn't disappoint! By adding just these two lines to our view,
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
We turn that pile of expletive into.....
Viola! Now we can finally say...