1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rails】Enumで複数選択(multiple: true)を使う時の備忘録

Last updated at Posted at 2023-03-24

概要

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(",")
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?