2

i have a rails project that has a simple mapped relation like below:

model categories

has_many :stories

model Story

belongs_to category

in my stories controller i have

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

then in my new.html.erb i have

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

i want to replace the <%= collection_select %>(select box) with <%= f.text_field%>(text field) and populate the data using jquery toxeninput javascript plugin and i dont know how to go about this.

user270014
  • 581
  • 3
  • 21
Uchenna
  • 4,059
  • 6
  • 40
  • 73

1 Answers1

2

I recently added jquery tokeninput to one of my projects and would try to give a rough step-by-step procedure to get it done:

  1. Get the token input javascript and css and add it to html
  2. Define a method search_category in your controller like following:

    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. init the jquery tokeninput like following:

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

Hope it helps!

rubish
  • 10,887
  • 3
  • 43
  • 57
  • How does your form look for the TokenInput part? – LearningRoR Jul 17 '11 at 07:30
  • 2
    form would be a normal `form_for @story` with category field defined as `f.text_field :category_id, :id => 'whatever'` – rubish Jul 17 '11 at 17:21
  • OK, Thank you. Perhaps you can answer my bounty since its pretty similar to what you've done. http://stackoverflow.com/questions/6674127/how-to-use-jquery-tokeninput-and-acts-as-taggable-on-together – LearningRoR Jul 17 '11 at 17:29
  • @Rubish I have a question about tokeninput thats probably very simple for you, mind taking a quick look? http://stackoverflow.com/questions/6819481/using-jquery-tokeninput-without-default-name – Jonah Katz Jul 25 '11 at 16:48