Rails 4.1开始引入Enum枚举。枚举值默认为数字。打算在数据库将枚举值保存字符串类。方便识别。本着优先使用Symbol而不是String的习惯。

模型定义为

class Account < ApplicationRecord
  enum account_type: { user: :user, }, _prefix: 'account_type'
end

通过account.save!正常保存无异常。通过ActionRecord查询后发现account_type为nil

2.5.1 :001 > Account.select(:account_type).first
Account Load (0.2ms) SELECT "accounts"."account_type" FROM "accounts" ORDER BY "accounts"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Account id: nil, account_type: nil>

通过rails dbconsole使用SQL语句查询确认数据库中account_type的确为user

sqlite> select account_type from accounts limit 1;
user

怀疑与枚举值使用Symbol有关。将枚举值:user修改为’user’

class Account < ApplicationRecord
  enum account_type: { user: 'user', }, _prefix: 'account_type'
end

之后ActiveRecord查询正常放回‘user’

2.5.1 :031 > Account.select(:account_type).first
Account Load (0.2ms) SELECT "accounts"."account_type" FROM "accounts" ORDER BY "accounts"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Account id: nil, account_type: 'user'>

Rails ActionRecord的Enum枚举可参考

ActiveRecord::Enum
https://api.rubyonrails.org/v5.2.0/classes/ActiveRecord/Enum.html

关于在 Rails Model 中使用 Enum (枚举) 的若干总结 · Ruby China
https://ruby-china.org/topics/28654

打赏

Leave a Reply

Your email address will not be published. Required fields are marked *