Skip to content Skip to sidebar Skip to footer

Rails Autocomplete Tags Separated By Commas Using Regex

I am using the old auto_complete plugin in conjunction with the acts as taggable on gem in an attempt to basically replicate the tagging behavior of Stack Overflow itself! I am mor

Solution 1:

I know this is old, but to recreate this behavior I used rails3-jquery-autocomplete with acts-as-taggable-on. They work very nicely and easily together.

// ModelclassFoo < ActiveRecord::Base
  acts_as_taggable_on :tags
end

// ControllerclassFoosController < ApplicationController
  autocomplete :tag, :name, :class_name =>'ActsAsTaggableOn::Tag'
  ...
end

// Routes
resources :foos do
  collection do
    get :autocomplete_tag_name
  end
end

//View
<% form_for :foo do |form| %>
  <%= form.label :tag_list, "Tags" %>
  <%= form.autocomplete_field :tag_list, autocomplete_tag_name_foos_path, :"data-delimiter" => ', ' %>
<% end %>

Hope that helps someone.

Solution 2:

I'd look into the options for the text_field_with_auto_complete helper. If it doesn't support what you need, I'd ditch it in favor of something you have more control over. My experience with helpers/plugins like this is that they only save you time if you're doing exactly what they expect you to do. If you need anything custom, you'll incur more pain trying to work around them than they're worth.

To ditch the text_field_with_auto_complete helper, look at the HTML and JS that it generates in the rendered page. Copy and paste that, then modify it to do what you need. You can still use the controller side of the autocomplete plugin.

The JS you'll want to split the string on commas will look something like this:

var tags = $('#myTextInput').value();
var splitTags = tags.split(/\w*,\w*/);

JS regexen are pretty similar to Ruby's. That regex will split on commas, eating extra whitespace.

Post a Comment for "Rails Autocomplete Tags Separated By Commas Using Regex"