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

StackOverflow https://stackoverflow.com/questions/4298476

Question

Consider the following parent/child relationship where Parent is 1..n with Kids (only the relevant stuff here)...

 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

The validates_presence_of methods on the Kid model works as expected on validation failure, generating a final string of Item is expected per the custom message attribute supplied.

But if try validates_with, instead...

 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 returns a NameError - uninitialized constant Parent::Kid error following not only an attempt to create (initial persist) user data, but also when even attempting to build the initial form. Relevant bits from the 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

The error suggests that somewhere during model name (and perhaps field name?) resolution for error message construction, something has run afoul. But why would it happen for some validates_* methods and not others?

Anybody else hit a wall with this? Is there some ceremony needed here that I've left out in order to make this work, particularly regarding model names?

Was it helpful?

Solution

After a few hours away, and returning fresh -- Was missing require "Kid" in Parent class. Will edit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top