2

嗨我正在使用繭產生嵌套字段。使用COCOON Rails的動態字段中的Jquery自動完成3

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

嵌套形式/字段是100%的工作等的Ive試圖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) 

的routes.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調用它。

任何解決方法將不勝感激。謝謝。

+0

我也需要這樣做。你有沒有破解它? – Bot 2013-07-23 10:21:33

回答

1

要做到這一點,你必須掛鉤繭回調。

立足我從繭的README例子解釋:

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

你仍然需要做一些像你這樣才能初始化動態添加之前已經呈現了itens。