true accepts_-6ren">
gpt4 book ai didi

validation - Rails3 : Nested model - child validates_with method results in "NameError - uninitialized constant [parent]::[child]"

转载 作者:行者123 更新时间:2023-12-03 18:08:29 30 4
gpt4 key购买 nike

考虑以下父/子关系,其中 Parent 是 1..n 与 Kids(此处仅相关内容)...

 class Parent < ActiveRecord::Base

# !EDIT! - was missing this require originally -- was the root cause!
require "Kid"

has_many :kids, :dependent => :destroy, :validate => true
accepts_nested_attributes_for :kids

validates_associated :kids

end

class Kid < ActiveRecord::Base

belongs_to :parent

# for simplicity, assume a single field: @item
validates_presence_of :item, :message => "is expected"

end

Kid 模型上的 validates_presence_of 方法在验证失败时按预期工作,根据提供的自定义消息属性生成 Item is expected 的最终字符串。

但是如果尝试validates_with,而不是...

 class Kid < ActiveRecord::Base

belongs_to :parent

validates_with TrivialValidator

end

class TrivialValidator

def validate
if record.item != "good"
record.errors[:base] << "Bad item!"
end
end

end

...Rails 返回一个 NameError - uninitialized constant Parent::Kid 错误,不仅在尝试创建(初始持久化)用户数据之后,而且在尝试构建初始表单时也是如此。来自 Controller 的相关位:

def new
@parent = Parent.new
@parent.kids.new # NameError, validates_* methods called within
end

def create
@parent = Parent.new(params[:parent])
@parent.save # NameError, validates_* methods called within
end

该错误表明在模型名称(也许还有字段名称?)解析错误消息构造期间的某处发生了冲突。但为什么某些 validates_* 方法会发生这种情况,而其他方法不会呢?

还有其他人用这个碰壁吗?为了完成这项工作,这里是否需要一些我遗漏的仪式,特别是关于模型名称?

最佳答案

离开几个小时后,新鲜返回 -- Parent 类中缺少 require "Kid"。将编辑。

关于validation - Rails3 : Nested model - child validates_with method results in "NameError - uninitialized constant [parent]::[child]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4298476/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com