2010-11-28 71 views
3

考慮以下父/子關係,其中Parent是1..n與Kids(僅此處相關內容) ...作品如預期驗證失敗Rails3:嵌套模型 - child validates_with方法導致「NameError - 未初始化常量[parent] :: [child]」

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 

在兒童模型中的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

經過幾個小時的路程,並返回新鮮 - 在Parent類缺少require "Kid"。將編輯。

+0

這對我來說看起來並不合適 - 你不應該需要另一個模型。 – 2010-11-29 02:25:45

相關問題