2009-11-07 53 views
1
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 

回答

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

+0

是的,这将工作,但没有办法将其移入模型? – Gavin 2009-11-07 20:42:17

+0

绝对。这只是一个irb会话;将其移入'Account.create_with_deposit!(attributes)'。 – 2009-11-08 15:50:06