You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在aasm中定义状态以保存为首字母大写字符串?

How to Configure AASM to Save Title Case Status Strings

Hey there! Great pick using AASM—it’s one of the most reliable gems for state management in Ruby/Rails projects. Let’s get your statuses saving in that Title Case format you need, like 'Draft' or 'Published'.

Step 1: Confirm Your Database Column

First, make sure your model’s status column is a string type (you probably already have this set up, but just double-check!). If not, you’d run a migration like this:

rails generate migration AddStatusToPosts status:string
rails db:migrate

Step 2: Configure AASM in Your Model

The key here is using the value option when defining each state. This lets you explicitly set the string that gets stored in the database, while still using clean, lowercase symbols for your state checks and events.

Here’s a full example for a Post model:

class Post < ApplicationRecord
  include AASM

  # Tell AASM to use the :status column for state storage
  aasm(column: :status) do
    # Define each state with its Title Case value
    state :draft, value: 'Draft'
    state :published, value: 'Published'
    state :archived, value: 'Archived'

    # Define your state transition events
    event :publish do
      transitions from: :draft, to: :published
    end

    event :archive do
      transitions from: :published, to: :archived
    end

    event :revert_to_draft do
      transitions from: [:published, :archived], to: :draft
    end
  end
end

How It Works

  • When you call post.publish!, AASM will update the status column to 'Published' (exactly the format you want).
  • You still get to use AASM’s handy state check methods like post.draft?, post.published?—these use the lowercase symbols, not the stored string, so your code stays clean.
  • If you want to disable exceptions for invalid state transitions (optional), add whiny_transitions: false to the aasm block, like:
    aasm(column: :status, whiny_transitions: false) do
      # ... states and events ...
    end
    

Quick Tips

  • If you have existing data, make sure to update any old status values to match the Title Case format (e.g., run a rake task or database query to change 'draft' to 'Draft').
  • You can verify the stored value by checking post.status after a transition—it should return the Title Case string you defined.

内容的提问来源于stack exchange,提问作者Abhishek Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:34:58