Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 正在验证ActiveRecord关联聚合?_Ruby On Rails 4_Activerecord - Fatal编程技术网

Ruby on rails 4 正在验证ActiveRecord关联聚合?

Ruby on rails 4 正在验证ActiveRecord关联聚合?,ruby-on-rails-4,activerecord,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_fo

验证关联聚合的好方法是什么。这必须发生在访问数据库时,即仅从模型的属性访问数据库时。我使用的是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
好吧,我想出来了

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