【发布时间】:2021-04-29 09:52:26
【问题描述】:
在我的 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 在实际保存记录之前不会返回任何货币。
如何解决这个问题?
【问题讨论】:
-
问题是
pluck是用来创建数据库查询的。由于未保存服务项目,因此不返回任何行。您想要#map、#select或任何其他可枚举的方法。
标签: ruby-on-rails rails-activerecord