我在 Rails 模型中有自定义属性设置器,我在其中添加了验证错误。然而,当记录属性被更新时,“真”返回结果,这让我有点困惑。任何提示如何在自定义设置器中使用验证错误?
模型:
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