Last active
April 10, 2024 11:03
-
-
Save tabishiqbal/32fe6c17f74c7da09c24d33feee77e26 to your computer and use it in GitHub Desktop.
Ruby on Rails simple multiple select using Tom-select
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= 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 %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Product < ApplicationRecord | |
has_many :product_categories | |
has_many :categories, through: :product_categories | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"], | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Screen.Recording.2023-08-12.at.4.39.28.PM.mov