2

嗨,我正在使用茧来生成嵌套字段。

茧:https ://github.com/nathanvda/cocoon

嵌套的表单/字段是 100% 工作的,所以我尝试将 jQuery 自动完成集成到一个嵌套字段中。

我一直在关注这个要点(从 map7 分叉):https ://gist.github.com/xirukitepe/5132317

自动完成功能在第一个/父字段中有效,但不适用于其他后续嵌套字段。

这是我的代码:

首先我创建了自动完成控制器....

class AutocompleteController < ApplicationController
    def categories
     if params[:term]
       like  = "%".concat(params[:term].concat("%"))
       categories = Category.where("lower (categories.code) LIKE lower(?)", like)
     else
       categories = Category.all
     end
     list = categories.map {|u| Hash[id: u.id, label: u.code, name: u.code]}
     render json: list            
   end
 end

然后在item.rb

我添加了 attr_accessor 和一种方法......

attr_accessor :category_code
def category_code
          category.code if category_id
end

items_controller.rb 中

def category_code=(code)
   category= Category.find_by_code(code)
   if category       
     self.category_id = category.id
   else              
     errors[:category_code] << "Invalid name entered"
   end               
end                 

def category_code      
   Category.find(category_id).name if category_id
end

这是我的咖啡文件:

$ ->
  $('input.x').autocomplete
  source: "/autocomplete/categories"
  select: (event,ui) -> $("input.xx").val(ui.item.id)

路线.rb

 match '/autocomplete/categories' => "autocomplete#categories"
  resources :project_procurement_management_plans do

    resources :attachments
    resources :items do

        member do
           put :edit_pmr_item
           get  :edit_item
        end
    end
  end

我通过类而不是 ID 调用它,因为嵌套属性具有不同的 IDS,我不知道如何使用 JS 调用它。

任何解决方法将不胜感激。谢谢。

4

1 回答 1

1

为此,您必须挂钩茧回调。

基于我在茧自述文件中的示例中的解释:

$('#tasks')
  .on('cocoon:after-insert', function(e, task_to_be_added) {
    task_to_be_added.autocomplete({
      source: "/autocomplete/tags"
    });
})

您仍然需要像您所做的那样初始化在动态添加之前已经渲染的itens。

于 2013-10-29T00:32:31.490 回答