Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 more or less doing what is described in this rails cast. For single tags, this works great. However, I would really like to make it so that every time the user enters a space or a comma (much like on Stack Overflow), the autocomplete will start anew. I'd imagine there is some way to do this via regex, but I'm not sure how to go about applying this behavior to the text_field (I'd imagine using JavaScript to "restart" the autocomplete, but admittedly I am fairly weak when it comes to JavaScript. This is what my view looks like:

<%= text_field_with_auto_complete :business, :tags, {}, { :url => formatted_businesses_path(:js), :method => :get, :with => "'search=' + element.value" } %>

My controller is very straightforward, simply saving the tags for that particular business.

If someone could point me in the right direction (As I'm not sure how to go about doing this) I would greatly appreciate it.

like image 939
goddamnyouryan Avatar asked Dec 20 '10 03:12

goddamnyouryan


2 Answers

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.

// Model
class Foo < ActiveRecord::Base
  acts_as_taggable_on :tags
end

// Controller
class FoosController < 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.

like image 58
chrisgooley Avatar answered Nov 17 '22 08:11

chrisgooley


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.

like image 40
Ian Avatar answered Nov 17 '22 08:11

Ian