Applying autocomplete with Rails and Semantic UI

Category: Ruby :: Published at: 28.05.2021

Creating autocomplete with Rails and Semantic UI is very easy, and you should not have problem with that. 
Semantic UI includes search library and all you need to do is just to write couple lines of code.

If you have your semantic-ui library installed all you need to do is just to apply javascript code, f.e.

        url: "/panel/cars/autocomplete?q={query}"
        results: "items",
        title: "brand"
      minCharacters : 3
        noResults: "No results"

The url field is a path to the JSON request which will return back your data.

Results field is a key which will include the data you want to see in your autocomplete list.

Title field is a key for every single item you will return.

So in the case above your json data should look moreless like:

 "items" => {
   "brand" => "Audi",
   "brand" => "BMW",
   "brand" => "Citroen",
   "brand" => "Dacia" 

 If you want to return this data in Ruby on Rails you need to create autocomplete method in the cars_controller.rb

def autocomplete
  render json: { items: cars_hash(params[:q]) }


def cars_hash(query)
  CarBrand.where("car LIKE ?", "%#{query}%")
    .each_with_object([]) { |car_brand, array| array << { "brand" => CarBrand.brand } }

The cars_hash method will scope only records matching query parameter (characters we wrote in the input). An each_with_object method will return an array with format prepared for Semantic UI search function.

- Click if you liked this article

Views: 302