Rails3: Nested model - method child validates_w method leads to "NameError - uninitialized constant [parent] :: [child]"

Consider the following parent / child relationships in which the parent: 1..n with children (only relevant material 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 for the Kid model work as expected when validation fails, generating the final string Item is expectedfor the provided custom message attribute.

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 an error NameError - uninitialized constant Parent::Kid, following not only the attempt to create (initial save) user data, but also when trying to create the original form. Corresponding 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

, - (, , ?) - . validates_*, ?

- ? - , , , ?

+3
1

- require "Kid" Parent. .

0

Source: https://habr.com/ru/post/1777332/


All Articles