activerecord枚举和脏属性

时间:2017-06-19 04:21:25

标签: ruby-on-rails activerecord enums

我有一个定义enum的模型,如此:

enum status: [ :init, :requested, :packed, :paid, :shipped ]

我还有以下使用脏属性的方法。

  def shipment_requested
    status_changed?(from: :init, to: :requested)
  end

  def shipment_packed
    status_changed?(from: :requested, to: :packed)
  end

  def shipment_paid
    status_changed?(from: :packed, to: :paid)
  end

  def shipment_shipped
    status_changed?(from: :paid, to: :shipped)
  end

有许多依赖于此的模型回调,例如更新时间戳和发送电子邮件。

但不幸的是,这一切都无效。

sh = Shipment.find(1)
sh.init?
=> true
sh.requested!
sh.requested?
=> true
sh.shipment_requested
=> false

以上代码有什么问题?这是一个错误吗?

我本可以在控制器上手动设置所有值,但是这违背了使用枚举的目的,根据上面的文档,它具有相当不错的功能,比如定义范围和方法来检查status

1 个答案:

答案 0 :(得分:3)

尝试将值作为字符串发送到changed?方法:

class Entry < ApplicationRecord
  enum type: [:single, :double, :triple]
end

e = Entry.first
e.type # => "single"
e.type = :double
# notice here values are strings, not symbols
e.type_change # => ["single", "double"]
e.type_changed?(from: :single, to: :double) # => false
e.type_changed?(from: "single", to: "double") # => true