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.

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

How does your form look for the TokenInput part?
form would be a normal form_for @story with category field defined as f.text_field :category_id, :id => 'whatever'
OK, Thank you. Perhaps you can answer my bounty since its pretty similar to what you've done. stackoverflow.com/questions/6674127/…
@Rubish I have a question about tokeninput thats probably very simple for you, mind taking a quick look? stackoverflow.com/questions/6819481/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.