gpt4 book ai didi

ruby-on-rails - activerecord 枚举和脏属性

转载 作者:行者123 更新时间:2023-12-05 01:44:50 25 4
gpt4 key购买 nike

我有一个定义 enum 的模型像这样:

枚举状态:[ :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

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

我本可以在 Controller 上手动设置所有值,但这违背了使用枚举的目的,枚举根据上面的文档提供了非常好的功能,比如定义范围和方法来检查 status

最佳答案

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

关于ruby-on-rails - activerecord 枚举和脏属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44622228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com