【问题标题】:Jquery Autocomplete in a Dynamic Field using COCOON Rails 3使用 COCOON Rails 3 在动态字段中自动完成 Jquery
【发布时间】:2013-03-01 00:23:04
【问题描述】:

您好,我正在使用 cocoon 生成嵌套字段。

茧: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)

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调用它。

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

【问题讨论】:

  • 我也需要这样做。你破解了吗?

标签: ruby-on-rails autocomplete jquery-autocomplete cocoon-gem


【解决方案1】:

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

基于我在 cocoon README 中的示例的解释:

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

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

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 2011-04-26
    • 2014-04-02
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多