ruby-on-rails - 针对同时创建的另一个模型上的属性进行验证
问题描述
我正在使用 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
上面的功能相同。
解决方案
推荐阅读
- angular - 如何在 Angular Universal 上获取页面加载时的登录状态
- .net - EditorTemplate 中的 .NET MVC 错误调用另一个 EditorTemplate
- excel - Libreoffice Calc 是否可以编辑图表图例的数据描述
- python - 如何在 databricks 中使用 openpyxl 将 Excel 保存到 Azure blob 存储
- java - 以编程方式创建一堆 Spring Bean 作为 HashMap
- javascript - 为什么我的 for 循环在“继续”之后没有重新评估条件?
- reactjs - 将自定义属性传递给预注册触发器 lambda 放大谷歌登录
- outlook-addin - 如何自定义 Outlook 功能区上下拉列表的项目数?
- llvm - 模块的第一个参数(操作码 llvm)
- node.js - Jest 应用程序导入来自 src,但超测试路由是 dist