如何在自定义设置器中添加活动记录验证错误?

Mik*_*kin 2 activerecord ruby-on-rails ruby-on-rails-3

我在Rails模型中添加了自定义属性设置器,在其中添加了验证错误。但是,当记录属性被更新时,结果返回“ true”,这让我有些困惑。有什么提示如何在自定义设置器中使用验证错误?

模型:

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
Run Code Online (Sandbox Code Playgroud)

控制台输出:

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
Run Code Online (Sandbox Code Playgroud)

我为这种情况制作了一个示例应用程序

Mik*_*kin 5

好的,我了解问题的核心。无法执行我想实现的目标,因为所有验证错误都会在验证过程开始后立即清除。

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

自定义二传手起步太早了:(


Zac*_* Xu 5

在您的 setter 中,您可以将错误消息存储在临时 hash 中。然后您可以创建一个 ActiveRecord 验证方法来检查此临时哈希是否为空并将错误消息复制到errors.

例如,

def age=(age)
  raise ArgumentError unless age.is_a? Integer
  self.age = age
rescue ArgumentError
  @setter_errors ||= {}
  @setter_errors[:age] ||= []
  @setter_errors[:age] << 'invalid input'
end
Run Code Online (Sandbox Code Playgroud)

这是 ActiveRecord 验证

validate :validate_no_setter_errors

def validate_no_setter_errors
  @setter_errors.each do |attribute, messages|
    messages.each do |message|
      errors.add(attribute, message)
    end
  end
  @setter_errors.empty?
end
Run Code Online (Sandbox Code Playgroud)

要查看此操作:

[2] pry(main)> p.age = 'old'
=> "old"
[3] pry(main)> p.save!
   (1.0ms)  BEGIN
   (1.2ms)  ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Age invalid input
[4] pry(main)> p.errors.details
=> {:age=>[{:error=>"invalid input"}]}
Run Code Online (Sandbox Code Playgroud)