Rails acts-as-taggable-on with select2 (and simple_form)
Asked Answered
A

3

7

I would like to have a select2 dropdown of tags, where i could select multiple existing tags and add new ones.

I have tried many different ways and i either don't get select2 box working or only one value is passed (last one).

This is closest i got (passes last value):

<%= f.input :tag_list, collection: @model.tags.map { |t| t.name }, input_html: { :style=> 'width: 300px', class: "taggable", data: { placeholder: "Tags" }} %>
Agneta answered 18/9, 2015 at 12:11 Comment(0)
A
4

As I mentioned before, normal select2 library now uses only select input types, but it does work with input types when using select2-full library.

So, this was a way out of one problem.

Still I had problems with only passing one single value. I was actually copy/pasting code from one of the examples and it was wrong. It was stated that strong parameters should include :tag_list, which is obvious, but it is actually {tag_list[]} that was needed in order to accept all the values.

Works like a charm now.

Agneta answered 21/9, 2015 at 12:17 Comment(1)
Your point about tag_list[] was crucial for me -- tags are being submitted as an array of strings like ["a", "b", "c"], not a single string like "a, b, c"Incus
Z
4

For me work this:

Coffee script:

  $( ".tags" ).select2
    theme: "bootstrap",
    tags: true
    tokenSeparators: [',']

and in the view:

= f.input :tag_list, input_html: { class: 'tags', multiple: "multiple" }, collection: @video.tag_list

Important part is multiple: "multiple"

And of course, how Mitja said, don't forget to put { tag_list: [] } to your controller strong parameters.

And as example, if you want to have your tags as suggestions in the dropdown, you could do this:

= f.input :tag_list, input_html: { class: 'tags', multiple: "multiple" }, collection: ActsAsTaggableOn::Tag.most_used(30), value_method: :name
Zimmer answered 9/10, 2015 at 10:2 Comment(0)
R
1

Try this one, hope this will work for you.

= f.input :tag_list, class: "taggable",data: {options: @model.tags.map { |t| t.name }} 

$(".taggable").select2(
  tags: $('.taggable').data('options')
  width: "252px"
);
Rossman answered 18/9, 2015 at 13:12 Comment(2)
Unfortunately it doesn't help. It seems like it has to be select type of input. So i added as: :select, otherwise it is just a normal input box. This way I now get dropdown, but with Yes and No options, not my tags. Additionally, it is not multiselect.Hageman
let me think about it.Rossman

© 2022 - 2024 — McMap. All rights reserved.