Skip to content

Instantly share code, notes, and snippets.

@tabishiqbal
Last active April 10, 2024 11:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tabishiqbal/32fe6c17f74c7da09c24d33feee77e26 to your computer and use it in GitHub Desktop.
Save tabishiqbal/32fe6c17f74c7da09c24d33feee77e26 to your computer and use it in GitHub Desktop.
Ruby on Rails simple multiple select using Tom-select
<%= form_with(model: product) do |form| %>
<div>
<%= form.label :name %>
<%= form.text_field :name, class: "input" %>
</div>
<div>
<%= form.label :categories %>
<%= form.collection_select :category_ids, Category.all, :id, :name, {}, {multiple: true, id: 'category-select', class: "dropdown"} %>
</div>
<%= form.submit "Save product", class: "btn-primary" %>
<% end %>
class Product < ApplicationRecord
has_many :product_categories
has_many :categories, through: :product_categories
end
class ProductsController < ApplicationController
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to admin_product_url(@product), notice: "Product was successfully created." }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
private
def product_params
params.require(:product).permit(:name, category_ids: [])
end
end
import TomSelect from "tom-select"
document.addEventListener("turbo:load", () => {
// Initializes a tom-select dropdown for elements with the 'category-select' ID.
// The 'remove_button' plugin adds functionality to remove selected items.
new TomSelect('#category-select', {
plugins: ["remove_button"],
});
})
@tabishiqbal
Copy link
Author

Screen.Recording.2023-08-12.at.4.39.28.PM.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment