无法通过jquery.tokeninput添加新标签

时间:2014-02-05 09:11:38

标签: ruby-on-rails acts-as-taggable-on jquery-tokeninput

我已经多次看过ryan rails-casts,但是我几天都坚持这个问题。主要问题是我无法使用jquery.tokeninput或没有jquery设置新的标记记录。我很确定它与错误的路线设置有关...提前谢谢你!

#prepopulating表单工作正常

_form.html.haml

= f.text_field :tag_list, data: {load: @job.tags.map(&:attributes).to_json }

job.js.coffee

jQuery ->
  $('#job_tag_list').tokenInput '/jobs/tags.json',
  theme: 'facebook'
  prePopulate: $('#job_tag_list').data('load')

job.rb

attr_accessible :tag_list


def self.tokens(query)

  tags = ActsAsTaggableOn::Tag.all.where("name LIKE ?", "%#{query}%")
  if tags.empty?
    [{id: "<<<#{query}>>>", name: "Add new skill:  \"#{query}\""}]
  else
    tags
  end
end


def self.tag_list=(arguments)
  return if !arguments.is_a?(Hash)
  list = arguments[:tag_list]
  list.gsub!(/<<<(.+?)>>>/) { ActsAsTaggableOn::Tag.find_or_create_by_name(name: $1).name }
end

jobs_controller.rb

def tags

  @tags  = ActsAsTaggableOn::Tag.where("tags.name LIKE ?", "%#{params[:q]}%")
  respond_to do |format|
    format.json {render :json => @tags.tokens(params[:q])}
  end
end

的routes.rb

    resources :jobs do
    member do
      post 'reply'
    end
  end

2 个答案:

答案 0 :(得分:1)

下面提供了act_as_taggable_one和jquery.tokeninput的可行集成:

从此处提取文件:https://github.com/loopj/jquery-tokeninput并输入相应的文件夹:

<强>供应商/资产/ Javascript角 * 供应商/资产/样式表 *

的Gemfile

gem 'acts-as-taggable-on'

application.css

 *= require token-input-facebook

的application.js

//= require jquery.tokeninput

application.html.erb

<%= javascript_include_tag :defaults, "jquery.tokeninput" %>

jobs.js.coffee

jQuery ->
  $('#job_tag_list').tokenInput '/jobs/tags.json',
    theme: 'facebook'
    prePopulate: $('#job_tag_list').data('load')
    allowCustomEntry: true

_form.html.haml

= f.text_field :tag_list, data: {load: @job.tags.map{|t| {id: t.name, name: t.name}}.to_json}

jobs_controller.rb

def tags
    @tags  = Job.tokens(params[:q])
    respond_to do |format|
      format.json {render :json => @tags}
    end
  end

job.rb

acts_as_taggable
attr_accessible :tag_list

def self.tokens(query)
    tags = ActsAsTaggableOn::Tag.where("tags.name LIKE ?", "%#{query}%")
    if tags.empty?
      [{id: "#{query}", name: "Add new skill:  \"#{query}\""}]
    else
      tags
    end
  end

的routes.rb

 resources :jobs do
    member do
      post 'reply'
    end
      get 'tags', on: :collection
  end

答案 1 :(得分:0)

$("#skills").tokenInput("/url",{
        theme: "facebook",
        onResult: function (results) {
            if ( results.length == 0 ){
              result = new Object();
              result['id']    = $('#token-input-skills').val();
              result['name']  = $('#token-input-skills').val();
              results.push(result);
            }
            return results;
        }
      });

我添加了一个函数,如果没有可用的结果,则使用用户的输入文本填充数组