- Add tom-select to Rails app
yarn add tom-select
- Add to 'app/javascript/stylesheets/application.scss'
@import "tom-select/dist/css/tom-select.bootstrap5";
PS Need bootstrap 5 library
- Add to 'app/javascript/packs/application.js'
import 'tom-select'
import TomSelect from "tom-select"
document.addEventListener("turbolinks:load", () => {
const selectInput = document.getElementById('select-tags')
if (selectInput) {
new TomSelect(selectInput, {
plugins: {
remove_button:{
title:'Remove this item',
}
},
persist: false,
// create: true,
create: function(input, callback) {
const data = { name: input }
const token = document.querySelector('meta[name="csrf-token"]').content
fetch('/tags', {
method: 'POST',
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(data)
})
.then((response) => {
return response.json();
})
.then((data) => {
callback({value: data.id, text: data.name })
});
},
onDelete: function(values) {
return confirm(values.length > 1 ? 'Are you sure you want to remove these ' + values.length + ' items?' : 'Are you sure you want to remove "' + values[0] + '"?');
}
})
}
})
- Create Tags controller (app/controllers/tags_controller.rb)
class TagsController < ApplicationController
def create
tag = Tag.new(tag_params)
if tag.valid?
tag.save
render json: tag
end
end
private
def tag_params
params.require(:tag).permit(:name)
end
end
- Add new route to: 'config/routes.rb'
resources :tags, only: :create
- Add to form input with id 'select-tags' (app/views/posts/_form.html.erb)
<div class="field">
<%= form.label :tags %>
<%= form.select :tag_ids, Tag.all.pluck(:name, :id), {}, { multiple: true, id: "select-tags" } %>
</div>
PS Check this in app/views/layouts/application.html.erb
<head>
...
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
....
</head>
async/await variant