【问题标题】:Why does validation of nested attributes not work on create?为什么嵌套属性的验证不适用于创建?
【发布时间】: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


【解决方案1】:

service_items 尚未添加到数据库中,因此pluck 不会返回任何有用的信息。您可以使用map 访问它,它使用内存中的对象。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    相关资源
    最近更新 更多