Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@henkm
Created May 2, 2011 19:55
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save henkm/952240 to your computer and use it in GitHub Desktop.
Save henkm/952240 to your computer and use it in GitHub Desktop.
Add new items via JQuery TokenInput / Ruby on Rails
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment