秘密在于你把错误放在哪里。查看自动保存关联的验证如何工作以获取线索:
def association_valid?(reflection, record)
return true if record.destroyed? || record.marked_for_destruction?
unless valid = record.valid?(validation_context)
if reflection.options[:autosave]
record.errors.each do |attribute, message|
attribute = "#{reflection.name}.#{attribute}"
errors[attribute] << message
errors[attribute].uniq!
end
else
errors.add(reflection.name)
end
end
valid
end
请注意错误是如何不添加到关联成员中的,而是添加到正在验证的记录中,违规属性以关联名称为前缀。你也应该能够做到这一点。尝试类似:
def matching_card_colors
color = nil
cards.each do |card|
if color.nil?
color = card.color
elsif card.color != color
# Note, there's one error for the association. You could always get fancier by
# making a note of the incorrect colors and adding the error afterwards, if you like.
# This just mirrors how autosave_associations does it.
errors['cards.color'] << "your colors don't match!"
errors['cards.color'].uniq!
end
end
end