概要
Enumで複数選択を初めて使ったときにすぐにやり方がわからなかったので、
今回は記事(Article)モデルに複数選択可のタグ(tags)カラムを追加する例でメモしました。
対応
マイグレーション
Articleモデルにtagsカラムを追加。
array: true
で配列対応しておくのがポイント。
(通常の文字列カラムだとrailsのコンソールでAticle.first.tagsとか入力して値を参照しようとするとデータがなぜか消えて困った)
../db/migrate/add_tags_to_articles.rb
class AddTagsToArticles < ActiveRecord::Migration[6.1]
def change
add_column :articles, :tags, :integer, array: true, default: []
end
end
モデル
Articleモデルにtagsのenumを設定する。
../app/models/article.rb
class Article < ApplicationRecord
extend Enumerize
# (中略)
enumerize :tags, in:{
hobby: 1,
cooking: 2,
travel: 3,
}, multiple: true
# (中略)
end
ビュー(Slim)
入力フォームでf.selectを使用する場合
tagsを複数選択できるようにselectタグで表示する。
../app/views/articles/_form.html.slim
h3.label 記事のタグ
= f.select :tags, Article.tags.options, { include_blank: false }, multiple: true
一覧表示などでカンマ区切りを表示する場合
.texts
で選択内容の配列が取得できるので.join
を使ってカンマ区切りで結合する。
../app/views/articles/_index.html.slim
h3 記事一覧
table
thead
tr
th = タイトル
th = タグ
tbody
- @articles.each do |article|
tr
td = article.title
td = article.tags.texts.join(",")