Using jquery TokenInput without default 'name'

被刻印的时光 ゝ 提交于 2019-11-30 23:37:46

The magical lines are

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

and

format.json { render :json => @authors.map(&:attributes) }

These lines convert the data read from table into the json which jquery-tokeninput can understand. It passes on all the data from the model into, jquery-tokeninput, but it is not necessary. Tokeninput, only needs two fields,

  1. id -> for each selected token, this is posted along with form
  2. name -> used as label of the token

If you don't want to have a name field in your model, and want to use account_number as the label, you can do it like following:

<%= f.text_field :author_tokens, "data-pre" => @book.authors.collect {|author| {:id => author.id, :name => author.account_number } } %>

and

format.json { render :json => @authors.collect {|author| {:id => author.id, :name => author.account_number } }

Basically, change the json passed to tokeninput. Pass accoun_number as name.

Update:

Change this line to something which better suits you:

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

One suggestion may be:

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

Remove the first %, but really depends on your data type and all.

Just add the "propertyToSearch" options :

$(function() {
  $("#user_tokens").tokenInput("/users.json", {
    crossDomain: false,
    propertyToSearch: "account_number",
    theme: "facebook",
  });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!