Rails将父错误与子错误合并

Abr*_*m P 12 ruby validation associations ruby-on-rails-3 rails-activerecord

我有以下两种(消毒/程式化)模型:

 class DrivingExam < ActiveRecord::Base
   belongs_to :dmv_rules
   has_many :invigilator_assignments, as: :assignable
   has_many :invigilator, through: :invigilator_assignments

   validate do |record|
     record.invigilator_assignments.each do |i|
       next if i.valid?
       i.errors.full_messages.each do |msg|
         errors.add_to_base(msg)
       end
     end
   end
 end



 class InvigilatorAssignment  < ActiveRecord::Base
   attr_accessible :invigilator_id

   belongs_to :assignable, polymorphic: true
   belongs_to :invigilator

   validates :invigilator_id, presence: true

   validates_each :invigilator do |record, attr, value|
     if record.assignable.is_a?(DrivingExam) && !value.no_scheduling_conflicts?
       record.errors.add attr, "This Invigilator has a scheduling conflict"
     end

   end
 end
Run Code Online (Sandbox Code Playgroud)

DrivingExamController通过以下方式调用这些:

 if @driving_exam.save
Run Code Online (Sandbox Code Playgroud)

预期的行为是模型应该在验证时返回false并将子消息加入父错误哈希并将其传递给控制器​​.

相反的是,页面无法使用422(这很奇怪)保存(这很好)并且不传递消息.

通过puts在上面的代码中添加语句,我已经确定:

1)if条件validates_each成功,record.errors因此数组在InvigilatorAssignment模型内部设置.

2)在validate do循环中,监考人员的分配是有效的,没有错误

3)validate do环中之前运行validates_each

所以问题是:我如何确保DrivingExam验证InvigilatorAssignment并将其错误消息合并到自己的错误哈希中.

Yah*_*hya 3

请参考 stackoverflow 上的这个问题:

Ruby on Rails:如何从显示的子资源获取错误消息?

它与你想要的类似。

  • 我已经参考了上面的 stackoverflow 帖子,实际上它已合并到我的 DrivingController 的验证循环中。但是,这似乎并不能解决我的问题。 (2认同)