使用jquery TokenInput而没有默认的'name'

Jon*_*atz 3 jquery ruby-on-rails railscasts jquery-tokeninput

我试图使用这里找到的jquery tokeninput:http://loopj.com/jquery-tokeninput/ 按照铁路指南的指南:http: //railscasts.com/episodes/258-token-fields

默认情况下,它需要表/ json上的"名称"列.

有任何方法可以自定义将其更改为其他内容(在我的情况下,'account_number')?

(在reailcast中,他说如果你没有'名字'栏,你需要额外的定制)

rub*_*ish 6

神奇的线条是

<%= f.text_field :author_tokens, "data-pre" => @book.authors.map(&:attributes).to_json %>
Run Code Online (Sandbox Code Playgroud)

format.json { render :json => @authors.map(&:attributes) }
Run Code Online (Sandbox Code Playgroud)

这些行将从表中读取的数据转换为jquery-tokeninput可以理解的json.它将模型中的所有数据传递给jquery-tokeninput,但这不是必需的.Tokeninput,只需要两个字段,

  1. id - >对于每个选定的令牌,这与表单一起发布
  2. name - >用作令牌的标签

如果您不希望name模型中有字段,并希望account_number用作标签,则可以执行以下操作:

<%= f.text_field :author_tokens, "data-pre" => @book.authors.collect {|author| {:id => author.id, :name => author.account_number } } %>
Run Code Online (Sandbox Code Playgroud)

format.json { render :json => @authors.collect {|author| {:id => author.id, :name => author.account_number } }
Run Code Online (Sandbox Code Playgroud)

基本上,更改传递给tokeninput的json.传递accoun_numbername.

更新:

将此行更改为更适合您的内容:

@authors = Author.where("name like ?", "%#{params[:q]}%")
Run Code Online (Sandbox Code Playgroud)

一个建议可能是:

@authors = Author.where("name like ?", "#{params[:q]}%")
Run Code Online (Sandbox Code Playgroud)

删除第一个%,但实际上取决于您的数据类型和所有.

  • 两个要确保,首先,在模型`account_number`中有一个字段`account_number`,第二,在collect的末尾添加`to_json`. (3认同)