Validation dependent on unsaved parent

I’m having trouble with a validation that depends on an attribute of a
belongs_to parent. If the child is added to an unsaved parent
(parent.children << new child), the has_many collection
parent.children includes the unsaved child. However the belongs_to
attribute child.parent appears to be nil until the parent has been
saved. Without access to the parent attributes, the validation can’t
be done in the child model. I have a sort-of workaround using
validation code in the parent, but that violates DRY. The validation
still has to be in the child because the child can be updated without
the parent validation coming into play.

Here’s the code:

=============

class Item < ActiveRecord::Base
has_many :parlevels
has_many :locations, :through => :parlevels
has_many :line_items
has_many :orders, :through => :line_items
end

class Location < ActiveRecord::Base
has_many :orders
has_many :parlevels
has_many :items, :through => :parlevels
end

class Parlevel < ActiveRecord::Base
belongs_to :item
belongs_to :location

#Attribute quantity is the max quantity of an item which may be
ordered for a location
end

class Order < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
belongs_to :location
end

class LineItem < ActiveRecord::Base
belongs_to :order
belongs_to :item

def parlevel
if self.order
Parlevel.find(:first, :conditions => {:location_id =>
self.order.location_id, :item_id => self.item_id})
else
nil
end
end

def validate
if self.quantity_requested

  if self.parlevel
    limit = self.parlevel.quantity
  else
    limit = 0
  end

  errors.add(:quantity_requested,"above maximum of " + limit.to_s)

if self.quantity_requested > limit
end
end
end

=============

The current result of this code in the limit is always zero when the
parent is unsaved. Not very useful.

Any suggestions?

-Mack

Here’s the solution:

http://macksmind.net/2008/04/26/using-belongs_to-in-rails-model-validations-when-the-parent-is-unsaved/

On Wed, Apr 23, 2008 at 10:54 AM, IndyCodeWarrior