Search code examples
ruby-on-railsruby-on-rails-3jqueryjquery-tokeninput

tokeninput in rails not working


I'm trying to run the tokeninput plugin on a field.

First of all the tutorial is mainly around adding id's from another associated model. I do not want to do that but just use a field from my own model (table) called tags.

currently when i type it it actions a /notes/tags.json ajax call but nothing is being returned, am i doing it right?

Controller:

class NotesController < ApplicationController
  helper_method :sort_column, :sort_direction
  respond_to :html, :json

  def index
    @notes = Note.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page])
    @tag = Note.where('tag LIKE ?', "%#{params[:q]}%")
  end

Model:

class Note < ActiveRecord::Base
  attr_accessible :name, :tag

  def self.search(search)
    if search
      where('name LIKE ?', "%#{search}%")
    else
      scoped
    end
  end
end

Solution

  • ok: this is a rough but working example using jquery autocomplete

    https://github.com/glennmartinez/QaBase/pull/1

    The steps are as follows:

    • make a route that responds to a json request (I hijacked the index action)
    • Either declare the path or the data itself in the data-autocomplete-source attribute on the text field eg: <%= f.text_area :my_token_field, 'data-autocomplete-source' => features_path
    • create the javascript which attaches to the field referencing the ID (check the html source for this)
    • submit the form and inspect the post-request-hash in the logger and run any before_save transformations you need to make the fields work.

    Using TOKENINPUT and following http://railscasts.com/episodes/258-token-fields AND looking at the example on the plugins page it expects your data to be in this format

    [
      {"id":"856","name":"House"},
      {"id":"1035","name":"Desperate Housewives"},
      ...
    ]
    

    You can create that same hash by referencing something different in the ID .. for example

    Notes.all.map { |n| {:id => n.tag, :name => n.name } }.to_json
    

    which will generate something like:

    [
      {"id":"tagname","name":"House"},
      {"id":"othertagname","name":"Desperate Housewives"},
      ...
    ]
    

    You can then tell the response fields to search the table by the tag name.

    Of course you will need to create some kind of uniqueness on these in order to manage only returning 1 record.

    I hope this helps.