Ask A Question

Notifications

You’re not receiving notifications from this thread.

Global Autocomplete Search Discussion

Awesome episode Chris! Thanks!

Reply

Great tut!

What if I want to put a thumb near the text?

Thanks!

Reply

i'm using this for "episodes" instead of "movies" so i have:

json.episodes do
json.array!(@episodes) do |episode|
json.title "Ep #{episode.episode}: #{episode.title}"
json.icon "#{episode.podcast.logo}"
json.url episode_path(episode)
end
end

json.podcasts do
json.array!(@podcasts) do |podcast|
json.title "#{podcast.title}"
json.icon "#{podcast.logo}"
json.url podcast_path(podcast)
end
end

and my search.js adds template function as well:

window.addEventListener("load", function() {
$input = $("[data-behavior='autocomplete']")

var options = {
getValue: "title",
url: function(phrase) {
return "/search.json?q=" + phrase;
},
categories: [
{
listLocation: "episodes",
header: "Episodes",
},
{
listLocation: "podcasts",
header: "Podcasts",
}
],
template: {
type: "iconLeft",
fields: {
iconSrc: "icon"
}
},
theme: "blue-light",
list: {
onChooseEvent: function() {
var url = $input.getSelectedItemData().url
$input.val("")
window.location = (url)
},
showAnimation: {
type: "fade",
time: 300,
callback: function() {}
},
hideAnimation: {
type: "fade",
time: 300,
callback: function() {}
},
}
}

$input.easyAutocomplete(options)
});

Reply

this is gold

Reply

Hey Chris Awesome Tutorial.
Can you do an Instagram like app tutorial with features like geolocation,tagging user in an image and hashtags

Reply

Chris thank you for this video, super helpful! I get a strange error though when following you at the end. In my navbar page - "undefined method `form_with' for #<#<class:0x007f875a6f8b58>:0x007f87600e0aa8>" I decided to hack away and switch form_with for form_tag but then I get an error on the line immediately below "undefined method `text_field' for nil:NilClass" I double checked my code and don't know what could be causing it. Any help would be amazing sir thanks :)
Github: https://github.com/OmarZV/s...

Reply

Hey Omar, in your gem file change rails gem to the latest: gem 'rails', '~> 5.1.1' or higher
consol: bundle update
Restart your rails application
Hope this works for you

Reply

Had the same issue and rewrote the form_tag, for code see my comment above

Reply

SHouldn't jquery and all dependencies be in /vendor/assets/javascripts folder? Just asking.. I thouhgt that is the 'recommended way'..

Reply

For anyone on Rails <5.1, this example code for `form_tag` can be used to replace `form_with`:

<%= form_tag('/search', local: true, method: :get, class: 'form-inline' ) do %>
<%= text_field_tag(:q, nil, data: { behavior: 'autocomplete' }, placeholder: 'Search', class: 'form-control mr-sm-2') %>
<%= button_tag('Search', class: 'btn btn-outline-success my-2 my-sm-0', type: 'submit') %>
<% end %>

or more readable as GitHub gist: https://gist.github.com/spe...

Reply
Phew... Thank you!
Reply

Hi Chris,

Thanks for this it has really helped me!

Does anyone know the best way to search multiple columns from model?

Something like : Search Movies by name and date and genre.

Any pointers would be appreciated!

Dan

Reply

Hi Chris, I'm trying to get my search form back to mobile responsive.
data: { behavior: "autocomplete" } in the form triggers easy-autocomplete functionality. But the search form/layout becomes mobile unresponsive when I add "data: { behavior: "autocomplete" } " Please do you know how I can fix this in the easy-autocomplete css file?

<%= form_with url: search_path, local: true, method: :get, :class => "" do |form| %>
<div class="input-group m-b-20">
<%= form.text_field :q, placeholder: "Search and select or hit enter", data: { behavior: "autocomplete" }, class: "form-control input-lg" %>

<button type="submit" class="btn btn-lg"></button>
</div>

<% end %>

Reply

if you're not using turbolinks (which i'm not), replace search.js with:

window.addEventListener("load", function() {
$input = $("[data-behavior='autocomplete']")

var options = {
getValue: "title",
url: function(phrase) {
return "/search.json?q=" + phrase;
},
categories: [
{
listLocation: "movies",
header: "Movies",
},
{
listLocation: "directors",
header: "Directors",
}
],
list: {
onChooseEvent: function() {
var url = $input.getSelectedItemData().url
$input.val("")
window.location = (url)
}
}
}

$input.easyAutocomplete(options)
});

Reply

Hi everyone! please i get this error "undefined method `ransack' for #<class:0x1135dad8>".

Reply

I got it... I had to restart the server. sorry for disturbing the conversation.

Reply

When I try to use .easyAutocomplete from console I get this error:

TypeError: $('input').easyAutocomplete is not a function. (In '$('input').easyAutocomplete(options)', '$('input').easyAutocomplete' is undefined)

And I get this as well that call css.map ????

http://localhost:3000/assets/easy-autocomplete.themes.cs... Failed to load resource: the server responded with a status of 404 (Not Found)

http://localhost:3000/assets/easy-autocomplete.css.map. Failed to load resource: the server responded with a status of 404 (Not Found)

I follow this tutorial but I get these error... Thank you very much if someone know how solve it!

Reply
Rodrigo, could you figure out  ? i have the same issue
Reply
Hi Chris I want to add a second search field to the search form, say to search for the location of the Directors. Just like yell.com, where you can enter the search term and the location in different text fields. Could you please help on how to write the ransack logic in the form and the main_controller?  
Thanks
Reply
Would love to see this in Vue within an app-wrapper (data-behavior='vue') like you talked bout in ep 239! I've been banging my head against a number of these options (https://github.com/vuejs/awesome-vue#autocomplete) within the context of a Rails app.
Reply
Hi Chris, 
At some stage you remove :

render json: {users: [], events: [], entreprises: []}

And from there i have

MainController#search is missing a template for this request format and variant. request.formats: ["application/json"] request.variant: []

Is there something your video is skipping please?

Reply
How can I fetch a full country name in the search.json.jbuilder. I am using the Country_select gem and autocomplete results is showing only a country short code like GB for United Kingdom.

Here is my code in the search.json.jbuilder:
json.movies do
  json.array!(@movies) do |movie|
    json.name movie.title.titleize + " " + "in" + " " + movie.country
    json.url movie_path(movie)
  end

movie.rb
 def country_name
    country = self.country
    ISO3166::Country[country]
   end
Reply

In your movie.rb change your country_name to:

 def country_name
    country_name = ISO3166::Country[country]
    country_name.translations[I18n.locale.to_s] || country_name.name
  end

Now you can do this movie.country_name which will convert your country code to the full name like this RU:Russia or CA:Canada, and etc:

# your code
json.name movie.title.titleize + " " + "in" + " " + movie.country_name
# your code
Reply

Thank you for the tutorial.

I get all of this to work until the final part of hooking it to the form field (I am using Bootstrap for forms).

I use the name "databehavior" rather than "data-behavior".
When I enter the field on the form I get autocomplete suggestions but they are from other inputs unrleated to the app. It seems that the search.js code is not being executed.

Any ideas?

Here is the form input code:
<%= form_with url: search_path, local: true, method: :get, html: {class: "form-inline my-2 my-lg-0" } do |form| %>
<%= form.text_field :q, placeholder: "College", data: { behavior: "autocomplete" },
databehavior: "autocomplete", class: "form-control mr-sm-2"%>
<% end %>

Here is the search.js code:
document.addEventListener("turbolinks:load", function() {
$input =$("[databehavior='autocomplete']")

var options = {
getValue: "name",
url: function(phrase) {
return "/search.json?q=" + phrase;
},
categories: [
{
listlocation: "users",
header: "Users",
}
]
}

$input.easyAutocomplete(options)
});

Reply

In case anyone looks at the post above, I have broken down the sequence into steps and have "proven" that the javascript runs correctly in the browser and that the controller is producing the JSON array. But nothing is showing up on the page. Any ideas on what could be the problem? How I could see the JSON object returned and in the browser and/or how it fails with the autocomplete gem?

Reply

I am getting an error when I run the finished code: search.js:31 Uncaught TypeError: $input.easyAutocomplete is not a function

However, when I put create an options variable directly in the console and run:
$input = $("[data-behavior='autocomplete']")
and then
$input.easyAutocomplete(options)

it works fine. Any idea why I am able to run easyAutocomplete directly in the console but not in the normal course of my app? Here is my application.js file:

// Rails functionality
window.Rails = require("@rails/ujs")
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("trix")
require("@rails/actiontext")

require("jquery")
require("easy-autocomplete")

require("custom/show")
require("custom/search")

// Tailwind CSS
import "stylesheets/application"

// Stimulus controllers
import "controllers"

// Jumpstart Pro & other Functionality
import "src/actiontext"
import "src/confirm"
import "src/direct_uploads"
import "src/forms"
import "src/timezone"
import "src/tooltips"

import LocalTime from "local-time"
LocalTime.start()

// ADD YOUR JAVACSRIPT HERE

// Start Rails UJS
Rails.start()

Any ideas on this? Thanks!

Reply

Nice

Reply

Is anyone else getting the following error when trying to search for a 2nd time?

TypeError: undefined is not an object (evaluating 'EasyAutocomplete.getHandle(b).getSelectedItemData')
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.