Ways to implement real-time search feature in Rails 4.2

Struggling to implement a basic search form with AJAX in my Rails 4.2 app, I've scoured numerous tutorials without success.

This is the search method I'm using:

  def self.search(search)
    search ? where('name LIKE ?', "%#{search}%") : all
  end

The index action in my controller:

  # GET /ticket_types
  # GET /ticket_types.json
  def index
    @ticket_types = TicketType.search(params[:search]).order(sort_column + " " + sort_direction).paginate(per_page: 10, page: params[:page])
    respond_to do |format|
      format.html {render 'index'}
      format.json {render json: @ticket_types.map(&:name)}
    end
  

The filter code:

  <form>
    <fieldset>
      <legend>Filter</legend>
        <%= form_tag path, remote: true, method: 'get', id: id do %>
          <%= hidden_field_tag :direction, params[:direction] %>
          <%= hidden_field_tag :sort, params[:sort]%>
          <p>
            <%= text_field_tag :search, params[:search], id: 'filter_search_autocomplete', data: {autocomplete_source: ticket_types_path} %>
            <%= render 'button_submit', name: nil, id:"search_button" %>
          </p>
        <% end %>
      </fieldset>
    </form>

The submit button code:

  <%= submit_tag "Search", name: name, class: 'button', id: id, remote: true %>

Content of ticket_types.coffee file:

jQuery ->
  $('#filter_search_autocomplete').autocomplete
  source: $('#filter_search_autocomplete').data('autocomplete-source')

Lastly, the index partial:

<p id="notice"><%= notice %></p>

<%= render 'registry_filter', path: ticket_types_path, id: "ticket_search_filter" %>
<%= render 'ticket_types' %>
<br>
<section id="content-area"></section>
<div>
  <%= render 'button_link', button_name: "Create", path: new_ticket_type_path, id: 'create' %>
  <%= render 'button_link', button_name: "Back", path: ticket_types_path, id: 'back_button' %>
</div>

I'm aiming to create a live search feature similar to Facebook's. When a user types a letter, it should display around 5 matching results. How can I turn this into a reusable partial for other models? Appreciate any input!

Answer №1

In my experience, I have tackled a similar task to what you are attempting to achieve.

If your data is stored in a database, one approach I recommend is converting the data to JSON within your Rails controller.

Once you have successfully converted your data to JSON, you can incorporate an input field with autocomplete functionality into your Rails form.

Below that, make sure to pass the JSON object path to your data option like this:

Example:

<%= f.text_field :some_name, data: {autocomplete_source: some_name_path} %>

In your controller, consider implementing something similar to the following code snippet. Utilizing Order and Where as scopes within your model is the preferred method:

  def index
    @some_name = SomeName.order(:field_name).where("feild_name like ?", "%#{params[:term]}%")

    respond_to do |f|
      f.json { render json: @some_names.map(&:field_name) }
    end
  end

After implementing the above steps, I utilized the autocomplete tool.

I hope the information provided proves helpful. If not, this RailsCast episode should guide you in the right direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering the Art of Concise Writing: Tips to

Is there a way to write more concisely, maybe even in a single line? this.xxx = smt.filter(item => item.Id === this.smtStatus.ONE); this.yyy = smt.filter(item => item.Id === this.smtStatus.TWO); this.zzz = smt.filter(item => item.Id == ...

A guide to extracting a Primitive Array from ES6 Promises

Currently, my goal is to load glsl scripts as strings by utilizing the ES6 Promise and Fetch APIs. In my attempt to achieve this, I believed that I had devised an elegant solution for fetching the vertex and fragment shaders and then generating a new progr ...

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

typescript error: passing an 'any' type argument to a 'never' type parameter is not allowed

Encountering an error with newUser this.userObj.assigned_to.push(newUser);, receiving argument of type 'any' is not assignable to parameter of type 'never' typescript solution Looking for a way to declare newUser to resolve the error. ...

The method of displaying the date is determined by the starting date

I have a pair of datepickers and I want the to date to be based on the selected from date. The to date should always be one day after the selected from date, ensuring they are not the same. For example: If I select 'from' 07/18/2018, the ' ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

To dismiss a popup on a map, simply click on any area outside the map

Whenever I interact with a map similar to Google Maps by clicking on various points, a dynamically generated popup appears. However, I am facing an issue where I want to close this popup when clicking outside the map area. Currently, the code I have writte ...

NodeJS introduces the nullish coalescing assignment operator (??=) for effective nullish value handling

Is it possible to use the Nullish coalescing assignment operator (??=) in NodeJS? const setValue = (object, path, value) => { const indices = { first: 0, second: 1 }, keys = path.replace(new RegExp(Object.keys(indices).join('| ...

Invoking a shared controller function in AngularJS from a separate controller

My main objective is to retrieve the current logged-in user by calling back to the server when a visitor lands on the site while still logged in. The challenge I face is determining which controller will be active since it's uncertain which page the v ...

In JSF, the @PostConstruct method will be triggered with each AJAX call, regardless of the fact that the managed bean has a view scope assigned to

Consider the following scenario. <h:form id="form" prependId="true"> <p:commandButton value="Submit" actionListener="#{testManagedBean.action}"/> <p:commandLink value="Submit" actionListener="#{testManagedBean.action}"/> </h:f ...

Implementing a transition to activate upon data loading in a Vue.js component – here's how!

Currently, I am immersed in a project utilizing vue.js and vue-router. Within my Vue application, I have a section dedicated to displaying news fetched from an API that functions as a blog. To load this news data into the component, I am utilizing the rou ...

triggers an unexpected error in console.log

I need help with the following code: function printName(obj) { console.log(obj.name); } printName({ name: "myName" }); (function displayError(errorMsg){ console.log(errorMsg); })("Error"); However, when I try to run this code, I am encountering a T ...

Guide on exporting a reducer from a Node module built on React Redux

I am currently working on a project that requires importing a component from an external node module. Both the project and the component utilize React and Redux, and I intend for them to share the same store. Below is a snippet of the reducer code for the ...

PHP Error: Function call to member unsuccessful

I'm currently experimenting with a tutorial that explains how to populate a Select2 drop down using data from a MySQL Database: Below is the PHP script I've slightly modified for this task: <?php // setting up the database connection ...

The bidirectional data binding feature is malfunctioning following an XMLHttpRequest request

When watching a property from Vuex, I use the following approach: computed: { ticket() { return this.$store.getters['order/reservation'].offer_id } }, watch: { ticket(newTicketId) { console.log('Caught change of ...

Using a combination of functions to ensure synchronicity in JavaScript operations

Here is the function I have created: $scope.saveManualResendDraft = function(todo) { if ($scope.editMode) { updateStartJobManual(); byeSendManualInputDirectly(); } else { console.log('bye'); } }; I have defin ...

Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value. ...

A Fresh Approach for Generating Unique UUIDs without Bitwise Operators

To generate UUIDs in TypeScript, I have implemented a method inspired by the solution provided on Stack Overflow. The code effectively converts JavaScript to TypeScript. generateUUID(): string { let date = new Date().getTime(); if (window.performa ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...

When making a jQuery + AJAX request, IE8 is causing a null return value

I'm completely stumped as to why this issue is happening. To start, the code has been checked and validated by the W3C validator as HTML5, except for some URL encoding problems (such as & needing to be &amp;), but I don't have the ability ...