gpt4 book ai didi

ruby-on-rails - 如何在自定义 setter 中添加事件记录验证错误?

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

我在 Rails 模型中有自定义属性 setter ,我在其中添加了验证错误。然而,当记录属性被更新时,'true' 作为结果返回,这让我有点困惑。任何提示如何在自定义 setter 中使用验证错误?

模型:

class Post < ActiveRecord::Base
attr_accessible :body, :hidden_attribute, :title

def hidden_attribute=(value)
self.errors.add(:base, "not accepted")
self.errors.add(:hidden_attribute, "not_accepted")
write_attribute :hidden_attribute, value unless errors.any?
end
end

控制台输出:
1.9.3p194 :024 > Post.last
Post Load (0.2ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT 1
=> #<Post id: 1, title: "asdsaD", body: "la", hidden_attribute: nil, created_at: "2013-11-13 16:55:44", updated_at: "2013-11-13 16:56:06">
1.9.3p194 :025 > Post.last.update_attribute :hidden_attribute, "ka"
Post Load (0.2ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT 1
(0.0ms) begin transaction
(0.0ms) commit transaction
=> true

我为此做了一个示例应用程序 case.

最佳答案

好的,我明白了问题的核心。不可能做我想要实现的目标,因为一旦验证过程开始,所有验证错误就会被清除。

https://github.com/rails/rails/blob/75b985e4e8b3319a4640a8d566d2f3eedce7918e/activemodel/lib/active_model/validations.rb#L178 .

自定义二传手太早了:(

关于ruby-on-rails - 如何在自定义 setter 中添加事件记录验证错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19960822/

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