2

我有一个 Rails 项目,它有一个简单的映射关系,如下所示:

型号类别

has_many :stories

模特故事

belongs_to category

在我的故事控制器中,我有

def new
@story = Story.new
@categories = Category.all
end

然后在我的 new.html.erb 我有

<%= form_for @story do |f| %>
<%= f.text_field, :title %>
<%= collection_select(:story, :category_id, @categories, :id, :name)%>
<% end %>

我想<%= collection_select %>用(文本字段)替换(选择框)<%= f.text_field%>并使用 jquery toxeninput javascript 插件填充数据,但我不知道该怎么做。

4

1 回答 1

2

我最近将 jquery tokeninput 添加到我的一个项目中,并尝试给出一个粗略的分步过程来完成它:

  1. 获取令牌输入 javascript 和 css 并将其添加到 html
  2. 在控制器中定义一个方法search_category,如下所示:

    def search_category
      # find the matching categories, Category.search method should implement all the logic needed
      categories = params[:q].blank? ? [] : Category.search(params[:q])
    
      render :json => categories.collect {|c| {:id => c.id, :name => c.name} }
    end
    
  3. 初始化 jquery tokeninput,如下所示:

    $("input#whatever").tokenInput("<%= search_category_path %>", {
      prePopulate: [{ 
                     id: "<%= @story.category.id %>", 
                     name: "<%= @story.category.name %>"
                   }],
      tokenLimit: 1 // limits only one selectable category
    });
    

希望能帮助到你!

于 2011-07-16T01:57:30.407 回答