Take the 2-minute tour ×

Ok, so I'm probably missing something obvious here. I'm using rails3-jquery-autocomplete and formtastic to allow the user to select a Category when creating an Item:

class Category < ActiveRecord::Base
  has_many :items

class Item < ActiveRecord::Base
  belongs_to :category

  validates :category_id, :presence => true

I got this working via:

semantic_form_for @item do |form|
  form.inputs do
    form.input :category_id, :as => :hidden
    form.autocompleted_input :category, 
                             :url => autocomplete_category_path, 
                             :id_element => "#item_category_id"

That all works fine and dandy; when the user selects the category name, the category_id goes into the hidden field, and the item saves appropriately.

However i run into problems validating when the user doesn't input/select a valid category. What is the appropriate way to validate the following cases:

  1. User types something in to the box that is not valid category. (this needs to fail. It fails now, but the inline errors are actually on the hidden field)
  2. User makes a selection, then changes the value of the text field to an invalid category (resulting in the id in the hidden field becoming stale. This should also fail, but instead it uses the stale selected Id)


share|improve this question
add comment

1 Answer

It seems like you are looking for jQuery Tokeninput. You just serve your categories via REST or include the JSON into the initialization

   tokenLimit: 1 // allow at most 1 item

<input type="text" id="mytokeninputfield" name="item[category_tokens]" data-pre="<%= @user.category_id %>"/>

See railscast #258 on tokenfields and my gem tokenizes as well (although I currently don't use it feel free to report bugs and I'll take care of it. Or just get inspired and do it on your own :) )

share|improve this answer
add comment

Your Answer


