I've got the following two (sanitized/stylized) models:
我有以下两种(消毒/程式化)模型:
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
These get called from the DrivingExamController
by way of:
这些通过以下方式从DrivingExamController调用:
if @driving_exam.save
The expected behaviour is that the model should return false on the validation and join the child messages into the parent errors hash and pass this up to the controller.
预期的行为是模型应该在验证时返回false并将子消息加入父错误哈希并将其传递给控制器。
What happens instead is that the page fails to save (this is good) with a 422(this is weird) and does not pass the messages.
相反的是,页面无法使用422(这很奇怪)保存(这很好)并且不传递消息。
By adding puts
statements throughout the above code, I have established that:
通过在上面的代码中添加puts语句,我已经建立了:
1) The if condition within validates_each
is successful, and the record.errors
array is thus set inside the InvigilatorAssignment
model.
1)validates_each中的if条件成功,因此在InvigilatorAssignment模型中设置了record.errors数组。
2) In the validate do
loop the invigilator assignment is valid and has no errors
2)在验证执行循环中,监考人员分配有效且没有错误
3) the validate do
loop runs before the validates_each
loop
3)validate do循环在validates_each循环之前运行
So the question is: How do I ensure that the DrivingExam
validates InvigilatorAssignment
and merges its error messages onto its own error hash.
所以问题是:我如何确保DrivingExam验证InvigilatorAssignment并将其错误消息合并到其自己的错误哈希中。
1 个解决方案
#1
2
Refer to this question on * :
请参阅*上的这个问题:
Ruby on Rails: how to get error messages from a child resource displayed?
Ruby on Rails:如何从显示的子资源中获取错误消息?
It is similar to what you want.
它类似于你想要的。
#1
2
Refer to this question on * :
请参阅*上的这个问题:
Ruby on Rails: how to get error messages from a child resource displayed?
Ruby on Rails:如何从显示的子资源中获取错误消息?
It is similar to what you want.
它类似于你想要的。