首页 > 解决方案 > 针对同时创建的另一个模型上的属性进行验证

问题描述

我正在使用 rails 6.1委托类型模式,并遵循 create 方法示例,但我遇到了需要针对父对象验证子对象的属性的场景。问题是在验证时,父对象没有保存,所以委托链不起作用。

说我希望我comment不超过entry.max_comment_length

class Entry < ApplicationRecord
  def self.create_with_comment(content, creator: Current.user)
    create! entryable: Comment.new(content: content), creator: creator
  end
end

module Entryable
  extend ActiveSupport::Concern

  included do
    has_one :entry, as: :entryable, touch: true
    delegate_missing_to :entry
  end
end

class Comment < ApplicationRecord
  include Entryable
  validate :max_length

  def max_length
    #max_comment_length delegates to Entry, but the value is nil at this point.
    comment_body.length < max_comment_length
  end
end

DHH 说:

[如果]您需要执行依赖验证,您应该构建一个工厂方法或类来处理复杂的需求。

但不详述,示例与create_with_comment上面的功能相同。

标签: ruby-on-railsruby

解决方案


推荐阅读