2009-11-07 45 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