LoginSignup
39
30

More than 5 years have passed since last update.

Ruby On Rails Gemまとめ -state_machine-

Last updated at Posted at 2014-06-12

state_machineとは

「state_machine」は公開・非公開、ON・OFFなどの属性の状態をよりシンプルに管理できるようにする。

インストール

Gemfileに以下を追加。

gem "state_machine"

ターミナルで$ bundle installを実行。

使い方

例として、Article(記事)モデルのカラム「status」に「下書き(draft)、公開(public)、非公開(private)」の3つの状態を保持し、また、「delete_flag」に「on、off」の2つの状態を保持するとします。

まずは、以下のように定義します。

$ rails g model Article status
article.rb
class Article < ActiveRecord::Base
  state_machine :status, initial: :draft do
    state :draft
    state :public
    state :private

    before_transition on: :draft, do: :preview_on  #状態の変更前に実行される
    after_transition draft: :public, do: :set_public_date  #状態の変更後に実行される

    event :change_status do
      transition draft: :public
      transition public: :private
    end
  end

  state_machine :delete_flag, initial: :off do
    state :on, value: 1
    state :off, value: 0

    event :delete_on do
      transition off: :on
    end

    event : delete_off do
      transition on: :off
    end
  end

  def set_public_date
    #公開日の設定、保存の処理
  end

  def preview_on
    #プレビュー機能をactiveに設定する処理
  end
end

使い方は、以下のようになります。

article = Article.new

"・statusの状態を表示"
article.status  # => "draft"(initialで初期がdraft)

"・イベント「change_status」を実行"
article.change_status
article.status  # => "public"(change_statusでdraftからpublicに変更)

"・statusはdraftか?publicか?"
article.draft?  # => false
article.public?  # => true

"・delete_flagの状態、valueを表示"
article.delete_flag_state  # => 0
article.delete_flag_name  # => :off(_nameだとシンボル)

"・イベント「change_status」を実行"
article.delete_on
article.delete_flag  # => "on"
39
30
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
39
30