Ruby on rails 4 正在验证ActiveRecord关联聚合?
验证关联聚合的好方法是什么。这必须发生在访问数据库时,即仅从模型的属性访问数据库时。我使用的是rails 4。例如: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 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