0

In my Ruby on Rails project (6.1), I have successfully installed acts-as-taggable-on (works from console and with ugly manual inputs), now I am trying to add selectize.js to it. I saw this here, but not sure how it is supposed to work. EDIT: I fixed the initial problem that I couldn't execute ruby code in JS - so now I have a .js.erb, an I changed the question accordingly.

I can:

  • successfully add ONE tag
  • successfully REMOVE a tag

I cannot:

  • properly display all tags in the form if there are multiple tags - the form shows as empty, and if I then select another tag (or create a new one) - everything is replaced by the one new tag (which kind of is consistent)... HOWEVER, when I check the entry BEFORE redisplaying the form - in a console for example - everything is ok, the proper tags ARE associated with that entry (I can do entry.tags and all is fine - one or more tags, as expected, are being displayed)
  • display new tags in the drop down. I THINK the problem is that the tags for the drop down are collected in the js.erb file - and that is not run / compiled every time a new tag is added...?

Here's the code from the form:

<%= form.text_field :tag_list, as: :string, class: "p-1 font-size-m mb-1 selectize-tags", id: 'tag-select' %>

and here is the JS (.js.erb):

 <%= all_tags = ActsAsTaggableOn::Tag.all.uniq.pluck(:id, :name) %>
  $(".selectize-tags").selectize({
    delimiter: ",",
    persist: true,
    allowEmptyOption: false,
    options: [
      <% all_tags.each do |t| %>
        {text: '<%=t[1] %>', value: '<%=t[1]%>' },
      <% end %>
    ],
    sortField: "text",
    create: function (input) {
      return {
        value: input,
        text: input,
      };
    },
  });
tkhobbes
  • 368
  • 3
  • 16
  • To use <% .. %> on your JS files, they must have the .js.erb extension and tell webpacker to include the files with this extension. Checkout [this](https://stackoverflow.com/questions/43945394/rails-5-1-webpacker-import-a-js-erb-file) – anonymus_rex Nov 30 '21 at 16:56
  • thanks - that fixed the ruby code in JS. However the function does not work - I can now select existing tags and associate with the model, but I cannot create new tags. If I add a new tag - the whole tag list gets erased. I updated my question above accordingly – tkhobbes Dec 01 '21 at 07:54

0 Answers0