LoginSignup
41
44

More than 5 years have passed since last update.

act-as-taggable-onを使ってタグを複数投稿する

Posted at

今回すること

タグを簡単に管理することができるgem act-as-taggable-onを使ってあるモデル(今回はprototype)を投稿する時、同時に複数のタグをつけられるようにします。

使用するファイル

  • gemfile
  • prototype.rb
  • prototypes_controlloer.rb
  • tags_controller.rb
  • prototype.new.html.haml
  • prototype/show.html.haml
  • prototype/show.html.haml
  • tags/index.html.haml

やり方

1 gemのインストール

gemfile
gem 'acts-as-taggable-on', '~> 3.4'

2 tagsテーブルを作成する

bin/rake acts_as_taggable_on_engine:install:migrations

bin/rake db:migrate

3 モデルにacts-as-taggable-onを追加する

prototype.rb
acts-as-taggable-on :prototypes

この設定で下記のメソッド
prototype.tag_list
が使えるようになります。

4 入力フォームを作成する

prototype.new.html.haml
=form_for(@prototype) do |f|
    = text_field_tag "prototype[tag][]", "", placeholder: "Web Design"
    = text_field_tag "prototype[tag][]", "", placeholder: "UI"
    = text_field_tag "prototype[tag][]", "", placeholder: "Application"
  = f.submit "投稿する"

= text_field_tag "prototype[tag][]"

ここでtagの後に[](空の配列)を使うことでタグを投稿したときに配列で扱うことができるようになります。

5 ストロングパラメータを設定する

prototypes_controlloer.rb
params.require(:prototype).permit(:title, :catch_copy, :concept, :user_id).merge(tag_list: params[:prototype][:tag])

6 入力したタグを表示する

tags_controller.rb
 def index
    @tags = ActsAsTaggableOn::Tag.most_used
 end

ActsAsTaggableOn::Tag.most_used

で最も使われているタグを取得することができます。most_usedに引数を渡すとその件数分取ってきますが、デフォルトでは20件取ってきます。

タグ一覧ページ

prototype.rb
acts_as_ordered_taggable_on :prototypes

タグ一覧ページで、タグが多い順に表示するようにします。

tags/index.html.haml
 - @tags.each do |tag|
   = link_to "#{tag.name}", tag_path(tag.id)
    = link_to tag_path(tag.id) do
      %i "#{tag.taggings.count}" Projects

link_toを入れ子にするときは、中のlink_toに do をつけ、第一引数をpathにします。

 プロトタイプ表示ページ

prototype/show.html.haml
%ul
  - prototype.tags.each do |tag|
    %li
      =link_to "#{tag.name}", tag_path(tag.id)

参考

http://ruby-rails.hatenadiary.com/entry/20150225/1424858414
(acts-as-taggable-on)

http://webos-goodies.jp/archives/51387214.html
(paramsを配列で扱う)

41
44
1

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
41
44