在我的 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
在实际保存记录之前不返回任何货币。
如何解决这个问题?
在service_items
尚未添加到数据库中,因此pluck
不会返回任何有用的东西。您可以使用 访问它map
,它使用内存对象。
def currencies
service_items.map(&:currency).uniq
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句