public
Last active

Add new items via JQuery TokenInput / Ruby on Rails

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#model (idea 100% stolen from ryanb)
def author_tokens=(ids)
ids.gsub!(/CREATE_(.+?)_END/) do
Author.create!(:name => $1).id
end
self.author_ids = ids.split(",")
end
 
# jquery.tokeninput.js
 
# remove .toLowerCase() (twice), otherwise you won't be able to add new items with capitals...
# also change this line:
# var this_token = $("<li><p>"+ value +"</p> </li>")
# to this:
# var this_token = $("<li><p>"+ value.replace('Add: ', '') +"</p> </li>")
 
# controller
def index
@authors = Author.where("name like ?", "%#{params[:q]}%")
results = @authors.map(&:attributes)
results << {:name => "Add: #{params[:q]}", :id => "CREATE_#{params[:q]}_END"}
 
respond_to do |format|
format.html
format.json { render :json => results }
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.