考虑以下父/子关系,其中 Parent 与 Kids 为 1..n(仅此处的相关内容)...
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
...RailsNameError - uninitialized constant Parent::Kid
不仅在尝试创建(初始持久)用户数据之后返回错误,甚至在尝试构建初始表单时也会返回错误。来自控制器的相关位:
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_*
而其他方法则不会呢?
还有人用这个撞墙吗?为了完成这项工作,这里是否需要一些我遗漏的仪式,特别是关于模型名称?