验证ActiveRecord关联聚合?

时间:2014-12-02 16:57:35

标签: ruby-on-rails-4 activerecord

验证关联聚合的好方法是什么。这必须访问数据库,这只是从模型的属性。我正在使用rails 4.例如:

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

1 个答案:

答案 0 :(得分: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