为什么嵌套属性的验证不适用于创建?

Why does validation of nested attributes not work on create?

在我的 Rails 6 应用程序中,我有以下设置:

class Quote < ApplicationRecord

  has_many :service_items, :dependent => :destroy

  accepts_nested_attributes_for :service_items, :allow_destroy => true

  validate :no_more_than_two_currencies

  def currencies
    service_items.pluck(:currency).uniq
  end

private

  def no_more_than_two_currencies
    if currencies.length > 2
      errors.add(:base, "Only two currencies are allowed")
    end
  end

end

不幸的是,验证仅适用于 update,不适用于 create

出于某种原因,service_items.pluck(:currency).uniq 在实际保存记录之前不会 return 任何货币。

如何解决这个问题?

service_items 尚未添加到数据库中,因此 pluck return 没有任何用处。您可以使用 map 访问它,它使用内存中的对象。

def currencies
  service_items.map(&:currency).uniq
end