gpt4 book ai didi

ruby-on-rails - 如何根据其他属性值添加自定义验证消息?

转载 作者:数据小太阳 更新时间:2023-10-29 07:38:10 25 4
gpt4 key购买 nike

我正在使用 Ruby on Rails 3.2.9,我只是想使用 state_machine gem 。我有以下声明:

# Model class attributes are:
#
# [String] status
# [Boolean] checkin_1
# [Boolean] checkin_2
#
class Article < ActiveRecord::Base
state_machine :attribute => :status, :initial => :unconfirmed do
state :confirmed, :value => 'confirmed'
state :unconfirmed, :value => 'unconfirmed'

event :confirm do
transition :unconfirmed => :confirmed
end

event :unconfirm do
transition :confirmed => :unconfirmed
end
end
end

我想在触发 confirm 事件和 checkin_1 和/或 checkin_2 时向实例对象添加自定义验证消息(避免保存这些对象) 值为 false。也就是说,假设我正在尝试确认以下每个对象:

<#Article id: 1, :status: 'unconfirmed', checkin_1: false, checkin_2: false>
<#Article id: 1, :status: 'unconfirmed', checkin_1: false, checkin_2: true>
<#Article id: 1, :status: 'unconfirmed', checkin_1: true, checkin_2: false>

然后我想避免保存对象并分别添加错误消息,如下所示:

"can not be confirmed if it is not checked for 1 and 2"
"can not be confirmed if it is not checked for 1"
"can not be confirmed if it is not checked for 2"

应该怎么做?

最佳答案

这样做怎么样:

state confirmed do
validate do
if !checkin_1 and !checkin_2
msg = "can not be confirmed if it is not checked for 1 and 2"
errors.add(:checkin_1, msg)
errors.add(:checkin_2, msg)
elsif !checkin_1
errors.add(:checkin_1, "can not be confirmed if it is not checked for 1")
elsif !checkin_2
errors.add(:checkin_2, "can not be confirmed if it is not checked for 2")
end
end
end

关于ruby-on-rails - 如何根据其他属性值添加自定义验证消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14001976/

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