Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Tags-Input with Rails4 / Simple_form

I'm Using Rails 4 with Simple_form and acts_as_taggable.

I'm Trying to implement the jQuery Tags Input for my Tags (atcs_as_taggable).

The HTML for the Tags_input is:

   <input name="tagsinput" class="tagsinput" value="School,Teacher,Colleague" />

which translates in Simple_form:

   <%= f.input :tag_list, input_html: { class: "tagsinput "} %>

Tags that i entered before the change are properly displayed in the Edit/form, but NEW tags arent Saved.

The JS for my Tags_input is simple:

   $(".tagsinput").tagsInput({
    width: '300px'
   });

What am i missing ?

like image 304
Mini John Avatar asked Dec 07 '22 05:12

Mini John


1 Answers

As for me, this plugin is not the best that you could use.

I would go with

  1. Chosen http://harvesthq.github.io/chosen/ or
  2. jQuery Tokeninput http://loopj.com/jquery-tokeninput/.

Used to like 2nd more, but Chosen is a great plugin that is my favorite now.

As for implementing them in rails:

Chosen

Gemfile

group :assets do
  gem 'chosen-rails'
end

app/assets/javascripts/application.js

//= require chosen-jquery

app/assets/stylesheets/application.css

*= require chosen

app/assets/javascripts/questions.js.coffee

jQuery ->
  $('#question_tags_ids').chosen()

questions/_form.html.erb

<div class="field">
  <%= f.label :tag_ids, "Tags" %><br />
  <%= f.collection_select :tag_ids, Tag.order(:name), :id, :name, {}, {multiple: true} %>
</div>

jQuery Tokeninput

app/assets/javascripts/application.js

//= require jquery.tokeninput

app/assets/stylesheets/application.css

*= require token-input-facebook

app/assets/javascripts/questions.js.coffee

jQuery ->
  $('#question_tag_tokens').tokenInput '/tags.json'
    theme: 'facebook'
    prePopulate: $('#question_tag_tokens').data('load')

questions/_form.html.erb

<div class="field">
  <%= f.label :tag_tokens, "Tags" %><br />
  <%= f.text_field :tag_tokens, data: {load: @question.tags} %>
</div>

models/question.rb

attr_accessible :name, :tag_tokens
attr_reader :tag_tokens

def tag_tokens=(tokens)
  self.tag_ids = Tag.ids_from_tokens(tokens)
end

tags_controller.rb

def index
  @tags = Tag.order(:name)
  respond_to do |format|
    format.html
    format.json { render json: @tags.tokens(params[:q]) }
  end
end

models/tag.rb

def self.tokens(query)
  tags = where("name like ?", "%#{query}%")
  if tags.empty?
    [{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
  else
    tags
  end
end

def self.ids_from_tokens(tokens)
  tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
  tokens.split(',')
end
like image 133
rmagnum2002 Avatar answered Dec 19 '22 16:12

rmagnum2002