LoginSignup
5
5

More than 5 years have passed since last update.

FlagShihTzuで無限に増えるboolean型カラムを一つのカラムで管理する

Posted at

無限に増えるboolean型カラム

例えば、「◯◯の通知を受け取る・受け取らない」とか、何とかフラグみたいなものを保持しようとすると、boolean型カラムで管理することになると思います。
これだと、通知のバリエーションとか、何とかフラグが増える度にmigrationが必要になってしまいだんだん辛くなってきます。。:sweat:

schema.rb
ActiveRecord::Schema.define(version: 2019_03_08_205817) do

  create_table "users", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "name"
    t.string "email"
    t.boolean "admin", default: false, null: false
    t.boolean "hoge_notification_receivable", default: false, null: false
    t.boolean "fuga_notification_receivable", default: false, null: false
    t.boolean "piyo_notification_receivable", default: false, null: false
    # ...
    # これではbooleanで管理したいものが増える度にmigrationが必要になってしまう・・
  end

end

migration不要でboolean値のバリエーション増加に対応する

その辛み、FlagShihTzuで解消できます!:innocent:

テーブルに integer型の flags カラムを追加し、

change_table :users do |t|
  add_column :users, :flags, :integer, default: 0, null: false
end

modelに FlagShihTzu をincludeして管理したいboolean値を定義するだけでOKです!

user.rb

class User < ActiveRecord::Base
  include FlagShihTzu   # FlagShihTzu をinclude

  # has_flagsでbooleanで管理したい値を定義する
  has_flags(
      1 => :admin,
      2 => :hoge_notification_receivable,
      3 => :fuga_notification_receivable,
      4 => :piyo_notification_receivable,
      # 何とかフラグが増えたらここに定義追加するだけでOK!
    )

  # 各フラグの初期値設定は after_initialize でやると良い
  after_initialize :assign_default_flags, if: :new_record?

  def assign_default_flags
    assign_attributes(
      admin: false,
      hoge_notification_receivable: true,
      fuga_notification_receivable: true,
      piyo_notification_receivable: true,
    )
  end
end

# 使う側は特に意識せずそのまま使える
user.admin # => true
user.hoge_notification_receivable # => false

導入手順や詳細はFlagShihTzuを参照してください。:grin:

5
5
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
5
5