gpt4 book ai didi

ruby-on-rails - 如何在 Rails 3 中的嵌套属性上手动设置错误?

转载 作者:行者123 更新时间:2023-12-01 09:03:03 26 4
gpt4 key购买 nike

如何在 Rails 3 中的嵌套属性上手动设置错误?

以下是我尝试过但对我不起作用的一些示例模型代码。

validate :matching_card_colors

has_many :cards
accepts_nested_attributes_for :card

def matching_card_colors
color = nil
cards.each do |card|
if color.nil?
color = card.color
elsif card.color != color
card.errors.add :color, "does not match other card colors"
end
end
end

最佳答案

secret 在于你把错误放在哪里。查看 autosave associations 验证如何工作以获取线索:

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

关于ruby-on-rails - 如何在 Rails 3 中的嵌套属性上手动设置错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13222720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com