Chris Bloom wrote:
> Alternate subject title: Validate child of unsaved parent based on
> grandparent attr?
> 
> I've got a create view with a form for both the parent object as well as
> multiple child objects. Upon submit, can I validate the parent and child
> objects before either are saved? There are a few caveats:
> 
> 1.) The validation of one attribute on all the child objects is based on
> an attribute of the parent's parent! (The grandparent object is already
> saved)
> 
> 2.) The parent object may have an attachment that must also be valid.
> (using attachment_fu)
> 
> class Project
>   has_one :settlement
> end
> 
> class Settlement
>   belongs_to :project
>   has_many :details,
>     :class_name => 'SettlementDetail',
>     :dependent => :delete_all do
>       def total_quantity
>         inject(0){|sum, p| sum + (p.quantity.nil? ? 0 : p.quantity)}
>       end
> 
>       def total_weight
>         inject(0){|sum, p| sum + (p.weight.nil? ? 0 : p.weight)}
>       end
>     end
> end
> 
> class SettlementDetail < ActiveRecord::Base
>   belongs_to :settlement
> 
>   validates_presence_of :quantity, :if => :quantity_required
> 
>   def quantity_required
>     ### TODO Will this work on a new detail object with an unsaved
>     ### parent settlement object?

Yes, as long as you set the settlement association of each
settlement_detail child you build to the new settlement object,
and also set the project association of that settlement object.

> 
>     if self.settlement.project.billing_method == "Weight"
>       # We don't need to validate because the billing method is Weight
>       return false
>     else
>       # Count is required
>       return true
>     end
>   end
> end


-- 
Rails Wheels - Find Plugins, List & Sell Plugins - http://railswheels.com

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to