简体   繁体   中英

Jquery Autocomplete faild with json response in Rails

I am trying to implement jquery-ui autocomplete into a rails application. I have following model into my rails application.

class Skill < ApplicationRecord
  has_many :user_skills
  has_many :users, through: :user_skills
  validates :name, presence: true, uniqueness: true
end

And I am trying to applying to autocomplete on skill name. I have created the following action into my home controller.

def skills_autocomplete
  @skills = Skill.order(:name).map(&:name)
  render json: @skills
end

And I defined this action into routes as:

get 'skills_autocomplete' => "home#skills_autocomplete"

And Below is the snippet of jquery autocomplete:

$(function() {
    var availableSkills = 'skills_autocomplete.json';
    $('#skills').autocomplete({
      source: availableSkills
    });
  });

But with this implementation when type any letter into search box this will show all the skills into autocomplete box. On the other hand if I user following implementation :

$(function() {
    var availableSkills = [".NET","ASP.NET","AWS","Android","Angular 1","Angular 2+","Bitbucket","Block Chain","C","C#","C++","CSS3","DevOpps","Django","Docker","Express Js","GIT","GITLAB","GraphQL","HTML5","Heroku","IoT","Ionic","JSON","Java","Javascript","Jquery","Jquery UI","MEAN Stack","Material Design","Mongo DB","Node Js","PHP + MySQL","PHP Laravel","Postgresql","Python","React Native","Ruby","Ruby on Rails","Sinatra","Symentic UI","Twitter Bootstrap","Wordpress","XML"]
  $('#skills').autocomplete({
    source: availableSkills
  });
});  

The autocomplete works fine. Can anyone please help what wrong I am doing here.

After looking on lot of options I observed that array returned as JSON response not processed by autocomplete. So I did something like this and got autocomplete worked fine now.

$(function() {
  var skills = 'skills_autocomplete.json';
  availableSkills = [];
  $.getJSON(skills, function(data){
    $.each(data, function(index, value){
      availableSkills.push(value);
    });
  });
  $('#skills').autocomplete({
    source: availableSkills
  });
});

Problem solved now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM