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

tro*_*ynt 3 ruby-on-rails ruby-on-rails-3

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

num*_*407 9

秘诀在于你把错误放在哪里.查看自动保存关联的验证如何为线索工作:

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

请注意错误不会添加到关联成员,而是添加到要验证的记录,前缀为关联名称的违规属性.你也应该能够做到这一点.尝试类似的东西:

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