LoginSignup
7
11

More than 5 years have passed since last update.

rails5でタグ機能をacts-as-taggable-onを用いて実装する方法

Last updated at Posted at 2019-05-13

概要

acts-as-taggable-onを使ってタグ機能を実装する方法です。
投稿にタグを複数登録できるようにし、indexやshowでタグのリンクがクリックされた際にそれと同じタグを持つ投稿を一覧表示させるところがゴールです。
もし間違い等あればご指摘の程よろしくお願い致します。

開発環境

Ruby on Rails 5.2.3

Gemfile

Gemfile
gem 'acts-as-taggable-on'
$ bundle install

僕は出なかったのですが、もしエラーが出る場合は

Gemfile
gem 'acts-as-taggable-on', :git => 'https://github.com/mbleigh/acts-as-taggable-on'

としてからbundle installするといいみたいです。

テーブル作成

$ rails acts_as_taggable_on_engine:install:migrations
$ rails db:migrate

Model

タグ機能をつけたいテーブルのmodelに

app/models/post.rb
acts_as_taggable

を追記。僕の場合はpostテーブルでした。

controllers

Strong Parametersに:tag_listを追記

app/controllers/posts_controller.rb
def post_params
  params.require(:post).permit(:title, :content, :tag_list)
end

アクションの変更

app/controllers/posts_controller.rb
def index
  if params[:tag]
    @posts = Post.tagged_with(params[:tag])
  else
    @posts = Post.all
  end
end

View

タグ用フォーム

app/view/posts/new.html.erb
<div class='field'>
    <%= f.label :tag_list %>
    <%= f.text_field :tag_list %>
</div>

リンク付きタグの表示

app/posts/show.html.erb
<p>tags: <%= raw(@post.tag_list.map { |t| link_to t, tag_path(t) }.join(', ')) %></p>

Routes

config/routes.rb
get 'tags/:tag', to: 'posts#index', as: :tag

これでタグをクリックすると同じタグがついているデータを一覧表示できるようになります。

参考

7
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
11