2015-05-06 124 views
0

我正在处理自动填充表单字段,并且在格式化JSON时遇到了一些问题,我想将其传递给此处。我使用的是ID字段的自动完成,虽然JSON正在返回如下:针对JQueryUI的JSON自动完成 - Rails

{"users":["12345","23456","34567", ... ]} 

据我了解,我需要的数据的JQuery的自动完成数组 - 我使用的 - 尽管我似乎不会失去围绕这一点的散列。有什么建议?或者如果我在其他地方出错,指导将会很棒!

以下是其他相关的代码如下:

JS

$(document).on('ready page:load', function(){ 
    $("#user_****Id").autocomplete({ 
     source: $('#user_****Id').data('autocomplete-source') 
    }) 
}) 

表(HAML)

= simple_form_for [:admins, @user] do |f| 
    ... 
    = f.input :****Id, input_html: { data: { autocomplete_source: new_admins_user_path } } 
    ... 

控制器

def new 
    @hospitals = Hospital.all 
    @hospitals_autocomplete = @hospitals.map(&:id) 

    respond_to do |format| 
     format.html 
     format.json {render json: @hospitals_autocomplete} 
    end 
    end 

谢谢大家 - 史蒂夫。

+0

调用show_user_tags我不知道HAML插入到jQuery的以任何方式。 'data-autocomplete-source'中有什么?看起来应该是一个字符串,而不是一个数组 – blgt

回答

0

,如果你正在寻找自动完成,我会建议Jquery TokenInput,我已经用它自己和它很容易setup.let我给你举个例子: -

在你的表单字段

<% form_for(@user,:url=>new_user_path) do |f|%> 

//other input text and text area fields 
//autocomplete field to add tag to user and also show existing tags 
//suppose this field is user_tag_list 
<%= f.text_field :tag_list, "data-pre" => @user.tags.map(&:attributes).to_json %> 
<%end%> 
在js代码

: -

//activate the autocomplete text field(user_tag_list) and call ajax to return json from the controller 
    $("#user_tag_list").tokenInput("https://stackoverflow.com/users/show_user_tags.json", { 
    crossDomain: false, 
    placeholder: "Add your Favorite user tags", 
    prePopulate: $("#user_tag_list").data("pre"), 
    theme: "facebook", 
    hintText: "Tag this user with your fav tags", 
    noResultsText: "Well,search for you fav tags", 
    searchingText: "here it comes <i class='fa fa-spinner fa-spin fa-lg'></i>", 
    tokenLimit:3, 
    //add title to search on basis of title on form submit 
    tokenValue: 'name', 
    resultsLimit:10, 
    resultsFormatter: function(item){ return "<li><p><span style='font-size:1em !important;'><b>" + item.name + "</b></span></p></li>" }, 
    tokenFormatter: function(item) { return "<li><p>" + item.name + "</p></li>" }, 
    preventDuplicates: true 
    }); 

控制器代码...在用户控制器

def show_user_tags 
    @tags = UserTag.where("title like ?", "#{params[:q].capitalize}%") 
    @tags = @tags.map do |c| 
     { :id => c.id,:name => c.title} 
    end 
    respond_to do |format| 
     format.html 
     format.json { render :json => @tags } 
    end 
end