考虑下面的父/子关系,其中Parent是1..n with 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
错误。来自控制器的相关位:
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_*
方法而不是其他方法?
还有其他人撞墙吗?这里是否需要一些我为了完成这项工作而遗漏的仪式,特别是关于模型名称?
答案 0 :(得分:0)
几个小时之后,又恢复了新鲜感 - 在require "Kid"
课程中遗失了Parent
。将编辑。