Reputation: 4089
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.
Upvotes: 2
Views: 879
Reputation: 10907
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:
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
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!
Upvotes: 2