【问题标题】:activerecord enum and dirty attributesactiverecord 枚举和脏属性
【发布时间】:2017-06-19 04:21:25
【问题描述】:

我有一个定义 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

【问题讨论】:

  • status_changed? 是什么?
  • AASM 正是为此类情况而设计的。
  • 尝试使用self.status_changed?(from: :init, to: :requested)
  • @Pavan 没用。我认为是 ! 在不运行验证的情况下保存模型,但我不确定我是否正在查看文档。我可能必须在模型中再次重新定义相同的方法才能使用没有update!的常规版本@

标签: ruby-on-rails activerecord enums


【解决方案1】:

尝试将值作为字符串发送到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

【讨论】:

  • 谢谢!有没有办法避免在模型脏属性方法中硬编码字符串文字?
  • 好吧,我怎么会错过这个? :) 不错!
  • @static 我只知道如何删除新值的字符串:e.type_was == "single" &amp;&amp; e.double?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多