2014-12-02 91 views
0

什么是验证关联聚合的好方法。这必须发生访问数据库,这是从模型的属性。我使用的轨道4.示例:验证ActiveRecord关联聚合?

rails g model Donation total:integer 
rails g model Donor name amount:integer 

class Donation < ActiveRecord::Base 
    has_many :donors, dependent: :destroy 
    accepts_nested_attributes_for :donors 
    # Donation.total :integer 
    validate :validate_donors_total_matches_donation_total 

    def validate_donors_total_matches_donation_total 
     # Need to figure out how to count the sum of all donors 
    end 
end 

class Donor < ActiveRecord:Base 
    belongs_to :donation 
end 

回答

0

好了,想通了......

private 
def validate_donors_total_matches_donation_total 
    # Need to figure out how to count the sum of all donors 
    all_donors = @association_cache[:donors].target 

    # Important to consider possible deletes... 
    if donors.reject(&:marked_for_destruction?).count > 0 
     subtotal = 0 
     data.each do |donor| 
      subtotal = subtotal + donor.amount 
     end 
     errors.add(:donors, "Donor amounts must add to Donation total. Now it's $#{subtotal}.") unless subtotal == total   
    else 
     # This can be done by itself using validates :donors, presence: true, I believe 
     errors.add(:donors, 'At least one syndicate is required') 
    end 
end