嵌套记录验证:需要一起验证子级和父级

时间:2009-11-07 11:35:13

标签: ruby-on-rails validation

Account < AR
  has_many :deposits
  accepts_nested_attributes_for :deposits
  attr_accessible :max_amount
end

Deposit < AR
  belongs_to :account
  attr_accessible :amount

  validate :validates_amount_less_than_max_amount

  def validates_amount_less_than_max_amount
    # How do you write this method?  When an Account is being created with a nested 
    # Deposit, it should do this validation, but account is nil until 
    # saved, so @contribution can't access the :max_amount and validate from it.
    # Solution?
  end
end

2 个答案:

答案 0 :(得分:0)

按预期使用此验证:

def validates_amount_less_than_max_amount
  errors.add(:amount, 'is more than max amount') if self.amount > account.max_amount
end

但如上所述,您无法同时使用new创建帐户和存款。尝试在交易中包装创建账户/存款:

>> Account.transaction do
>> a = Account.create!({:max_amount => 1000})
>> a.deposits_attributes = [{:amount => 1500}]
>> a.save!
>> end
ActiveRecord::RecordInvalid: Validation failed: Deposits amount is more than max amount

有关更多示例,请参阅what's new in edge rails 2.3

答案 1 :(得分:0)

以下是答案:

https://rails.lighthouseapp.com/projects/8994/tickets/2815-nested-models-build-should-directly-assign-the-parent

补丁计划为2.3.5。如果您现在需要该功能,则必须应用它及其依赖项。