rails3-jquery-autocomplete在Rails 3.2.1中不起作用?

时间:2012-02-25 08:30:31

标签: ruby-on-rails

我有发布标记模型:

class Post < ActiveRecord::Base
  has_and_belongs_to_many :tags

  def tag!(tags)
    tags = tags.split(" ").map do |tag|
      Tag.find_or_create_by_name(tag)
    end
    self.tags << tags
  end
end

class Tag < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

模式:

  create_table "tags", :force => true do |t|
    t.string "name"
  end

posts/_form的一部分:

  <div class="field">
    <%= f.label :tags %>
    <%= text_field_tag :tags, params[:tags] %>
  </div>

我跟踪了gem的git存储库中的instructions

控制器/ posts_controller.rb:

class PostsController < ApplicationController
  before_filter :authenticate_user!, :except => [:show, :index]
  autocomplete :tags, :name

(等)

routes.rb中:

resources :posts do
  get :autocomplete_tags_name, :on => :collection
end

所有JavaScripts文件都在那里:

 <script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script>
 <script src="/assets/jquery-ui.js?body=1" type="text/javascript"></script>
 <script src="/assets/autocomplete-rails.js?body=1" type="text/javascript"></script>

但绝对没有任何反应(我通过控制台添加标签对此进行了测试)。

有什么建议让这个宝石有效吗? (我在Rails 3.2.1上)

1 个答案:

答案 0 :(得分:2)

首先,你可以整理你的复数(无论如何都可以工作但是更容易与指令比较)

controllers / posts_controller.rb:

autocomplete :tag, :name

<强>的routes.rb

resources :posts do
    get :autocomplete_tag_name, :on => :collection
end

然后,您需要将text_field_tag更改为autocomplete_field,就像说明中的视图一样。

根据说明

form_for @product do |f|
    f.autocomplete_field :brand_name, autocomplete_brand_name_products_path
end

我建议您使用Rails表单帮助器form_for。在你使用部分的情况下,它看起来像这样:

views / posts / new.html.erb(或您将其称之为部分的地方):

form_for(:product, :url => {:action => 'create'}) do |f| # I've found that @product doesn't work on new creations and therefor I use :product
    render(:partial => "form", :locals => {:f => f})
    f.submit
end

<强>视图/帖/ _form.html.erb

<div class="fields">
    f.label :name, "Tag"
    f.autocomplete_field :tag_name, autocomplete_tag_name_products_path
</div>