Search code examples
ruby-on-railsacts-as-taggable-on

Is it possible to manage all tags (add, edit and delete) with acts-as-taggable-on


I use the acts-as-taggable-on gem with only one (default) tag list. I wonder whether it is possible to create a form to manage tags with the following features. (Went through all answers and only found solutions for Activeadmin.)

  1. I managed to get a list of all tags (across associated models) using ActsAsTaggableOn::Tag.all.
  2. I want to be able to edit each tag name (text input field).
  3. I want to be able to delete (destroy) a tag (checkbox).
  4. Lastly I want to be able to add a tag to the list as we use only categories user can add to different models. (maybe with find_or_create_with_like_by_name)

How would I construct the two forms 1-3 and 4? Is that at all possible with acts_as_taggable? Thanks for any hint in advance.


Solution

  • Solved it myself.

    View

    Add tags

    form_tag "/tags" do
      text_field_tag :name
      submit_tag "Add tag"
    

    Update and delete tags

    @tags.each do |tag|
      text_field_tag "tags[#{tag.id}]name", tag.name, class: 'name'
      <button class="update-tag radius small">Save</button>
      <button class="delete-tag radius small">Delete</button>
    
    
    $(function(){
      $(".delete-tag").on("click", function(){
        var row = $(this).closest("tr");
        $.post("/tags/" + row.data("id"), {_method: "DELETE"}, function(){
          row.remove();
        })
      })
    
      $(".update-tag").on("click", function(){
        var row = $(this).closest("tr");
        $.post("/tags/" + row.data("id"), {_method: "PUT", name: row.find('.name').val()})
      })
    })
    

    Controller

    class TagsController < ApplicationController
      def create
        name = params[:name]
        ActsAsTaggableOn::Tag.create(name: name)
        redirect_to :back
      end
    
      def destroy
        tag = ActsAsTaggableOn::Tag.find(params[:id])
        tag.destroy
        render json: {success: true}
      end
    
      def update
        tag = ActsAsTaggableOn::Tag.find(params[:id])
        tag.update_attributes(name: params[:name])
        render json: {success: true}
      end
    end