[RUBY] Add a tag function to Rails. Use acts-as-taggable-on

Overview

I added the tag function using gem acts-as-taggable-on in Rails. The function I added is a tag function that allows you to prepare existing tags (in the seed file) from new posts and select multiple from them. The image below. スクリーンショット 2020-07-16 22.58.40.png

environment

Ruby 2.5.7 Rails 5.2.4.2 Use design Bootstrap

Implementation

① Installation

Gemfile.


gem 'acts-as-taggable-on', '~> 6.0'

Terminal.


$ bundle install

② Create a table

Terminal.


$ rails acts_as_taggable_on_engine:install:migrations

$ rails db:migrate

③ Added to model and controller

app/models/style.rb


class Style < ApplicationRecord
    acts_as_taggable  #add to
end

In index, the tag list and what is tagged when the tag is pressed are displayed.

app/controllers/styles_controller.rb


def index
    @tags = ActsAsTaggableOn::Tag.all
    #List of tags
    if params[:tag]
      @styles = Style.tagged_with(params[:tag])
      #When searching for a tag, the one that has the tag removed is displayed.
    else
      @styles = Style.all
    end

def new
    @style = Style.new
    @tags = ActsAsTaggableOn::Tag.all
end

def show
    @style = Style.find(params[:id])
end

def create
    @style = Style.new(style_params)
    @style.user_id = current_user.id
    if @style.save
      flash[:notice] = "I registered the style"
      redirect_to style_path(@style.id)
    else
      @tags = ActsAsTaggableOn::Tag.all
      render :new
   end
end
#Since update and destroy have the same shape, they are omitted.

private

def style_params
      params.require(:style).permit(:name, :user_id, :image, tag_list: [])
      #  tag_list: []Added
end

end

④ Add to seed file This time, we will prepare an existing tag, so use the seed file.

db/seeds.rb


#Tagged tying(%w()Described in)
array = %w(Cute Natural Elegant Mode Women's Mash Men's Mash Short Bob Inner Roll Bob Short Layer Long Layer Layer Women's Perm Men's Perm Men's Cut Men's Two Block Women's Two Block Mohican Men's Business Girls Boys Students Mrs. Balayages Mesh Gradient Color Celebrity Braided Wedding Ceremony Party Casual Makeup Cute Makeup Mode Makeup Natural Makeup Elegant Makeup Adult Ceremony Men's Wolf Women's Wolf Gradient Bob Outer Hane Bob Front Down Sporty Gray Hair Inner Color Earring Color Men's Perm Women's Perm Men's Mesh Men's Color)
array.each{ |tag|
  tag_list = ActsAsTaggableOn::Tag.new
  tag_list.name = tag
  tag_list.save
}

Terminal.


$ rails db:seed

⑤ Describe in view


<div class="col-xs-12">
   <% @tags.each do |tag| %>
      <%= link_to "#{tag.name}(#{tag.taggings_count})", tag_path(tag.name), class: "label label-default" %>
   <% end %>
</div>
<%= form_for @style do |f| %>
  <div class="col-xs-12">
・ ・ ・ ・ ・ ・ ・
    <label class="col-sm-12">tag</label>
      <div class="col-sm-12">
        <% @tags.each do |tag| %>
          <%= f.check_box :tag_list, { multiple: true }, "#{tag.name}", nil %>
          <%= f.label " #{tag.name}(#{tag.taggings_count})", class: "label label-default" %>
        <% end %>
      </div>

      <div class="col-sm-12 text-right">
        <%= f.submit "Create New", class: "btn btn-danger" %>
      </div>
   </div>
  </div>
<% end %>
<label class="col-sm-12 my-top">
   <%= raw(@style.tag_list.map { |t| link_to t, tag_path(t), class: "label label-default" }.join(' ')) %>
</label>

The above will look like the following.

The index tagged_with (params [: tag]) narrows down the tags. Click the tag to display the data linked to the tag. In # {tag.name}, the tag name is displayed. # {tag.taggings_count} shows the number of registered tags. This completes the implementation.

Supplement

When deploying to production environment, I got an error with acts-as-taggable-on. If you get an error, please refer to it. I need to modify the tag table,

db/migrate/・ ・ ・_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb


t.references :tag, foreign_key: { to_table: ActsAsTaggableOn.tags_table }

Despite setting the above foreign key

db/migrate/・ ・ ・ ・_add_missing_unique_indices.acts_as_taggable_on_engine.rb


remove_index ActsAsTaggableOn.taggings_table, :tag_id if index_exists?(ActsAsTaggableOn.taggings_table, :tag_id)

It looks like you're trying to drop the index without dropping the foreign key.

So it worked when I made it like the following.

db/migrate/・ ・ ・ ・_add_missing_unique_indices.acts_as_taggable_on_engine.rb


# This migration comes from acts_as_taggable_on_engine (originally 2)
if ActiveRecord.gem_version >= Gem::Version.new('5.0')
  class AddMissingUniqueIndices < ActiveRecord::Migration[4.2]; end
else
  class AddMissingUniqueIndices < ActiveRecord::Migration; end
end
AddMissingUniqueIndices.class_eval do
  def self.up
    add_index ActsAsTaggableOn.tags_table, :name, unique: true

    # remove_index ActsAsTaggableOn.taggings_table, :tag_id if index_exists?(ActsAsTaggableOn.taggings_table, :tag_id)
    #Comment out the above
    if index_exists?(ActsAsTaggableOn.taggings_table, :tag_id) #add to
      remove_foreign_key :taggings, :tags                      #add to
      remove_index ActsAsTaggableOn.taggings_table, :tag_id    #add to
    end
    remove_index ActsAsTaggableOn.taggings_table, name: 'taggings_taggable_context_idx'
    add_index ActsAsTaggableOn.taggings_table,
              [:tag_id, :taggable_id, :taggable_type, :context, :tagger_id, :tagger_type],
              unique: true, name: 'taggings_idx'
  end

  def self.down
    remove_index ActsAsTaggableOn.tags_table, :name

    remove_index ActsAsTaggableOn.taggings_table, name: 'taggings_idx'

    add_index ActsAsTaggableOn.taggings_table, :tag_id unless index_exists?(ActsAsTaggableOn.taggings_table, :tag_id)
    add_index ActsAsTaggableOn.taggings_table, [:taggable_id, :taggable_type, :context], name: 'taggings_taggable_context_idx'
  end
end

Here, I referred to the following. https://teratail.com/questions/224720

In the development environment, I got an error with gem where there was no problem, so I was impatient ... I'm glad if you can use it as a reference.

Recommended Posts

Add a tag function to Rails. Use acts-as-taggable-on
Add a search function in Rails.
[Rails] Tag management function (using acts-as-taggable-on)
Convert to a tag to URL string in Rails
[rails] tag ranking function
How to make a follow function in Rails
I want to use a little icon in Rails
I want to define a function in Rails Console
I want to add a delete function to the comment function
[Rails] How to use enum
[Rails] How to use enum
How to use rails join
[Rails] Add column to devise
[Rails] How to use validation
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
[Rails] How to use Scope
[Rails 6.0] I implemented a tag search function (a function to narrow down by tags) [no gem]
[Rails] How to use gem "devise"
How to add columns to a table
[Rails] How to use flash messages
Preparing to create a Rails application
Function is very easy to use
How to use Ruby on Rails
[Rails] How to add new pages
Create a filtering function using acts-as-taggable-on
[Rails] How to use Active Storage
[Rails] Add strong parameters to devise
How to add the delete function
[Introduction to Rails] How to use render
[Rails] Add a confirmation screen and a completion screen to devise membership registration.
[Rails] How to put a crown mark on the ranking function
[Rails] Implementation of tag function using acts-as-taggable-on and tag input completion function using tag-it
(Ruby on Rails6) Create a function to edit the posted content
I tried to make a group function (bulletin board) with Rails
[Xcode] How to add a README.md file
A memorandum on how to use Eclipse
Migration file to add comment to Rails table
How to use custom helpers in rails
[Ruby on Rails] How to use CarrierWave
[Java] How to use the hasNext function
[Rails] How to use rails console with docker
[Rails] How to use ActiveRecord :: Bitemporal (BiTemporalDataModel)
[Rails] How to use the map method
How to add a new hash / array
[Rails withdrawal] Create a simple withdrawal function with rails
[Rails] Use validation on a specific controller
How to use MySQL in Rails tutorial
Make a login function with Rails anyway
Steps to set a favicon in Rails
[Rails] [Memo] When to add = to <%%> and when not
[Ruby on Rails] How to use redirect_to
[rails] How to create a partial template
[Note] How to use Rails 6 Devise + cancancan
[Processing × Java] How to use the function
[Ruby on Rails] How to use kaminari
[Rails] How to create a table, add a column, and change the column type
[Rails] Enum is easier to use! Enumelize!
[Rails] How to use video_tag to display videos
[Rails] How to use helper method, confimartion
How to use credentials.yml.enc introduced in Rails 5.2