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
1
A
回答
0
這裏的答案:
補丁定於2.3.5。如果您現在需要該功能,則必須應用它及其依賴項。
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. Rails的驗證孩子與父母
- 2. 嵌套模型和父驗證
- 3. ASP驗證器:僅驗證小寫字母和大寫字母
- 4. 嵌套UpdatePanel驗證
- 5. Firebase。驗證孩子記錄的規則
- 6. SQLite3記錄驗證
- 7. 驗證CNAME記錄
- 8. 驗證嵌套模型?
- 9. 驗證嵌套的ViewModels
- 10. 嵌套控件驗證
- 11. Aurelia驗證嵌套對象
- 12. rails驗證嵌套屬性
- 13. 嵌套形式驗證
- 14. 必需的驗證器和比較驗證器不起作用!
- 15. Rails 3失敗驗證父模型驗證嵌套屬性失敗
- 16. XML驗證,嵌套XSD和UNC路徑
- 17. 基於父屬性驗證孩子
- 18. 驗證該部分的總和等於與父母總/兒童記錄
- 19. SQL JOIN父母和孩子和GET父母和孩子記錄計數
- 20. @PreAuthorize(permitAll)仍需要驗證
- 21. 我需要驗證jwt嗎?
- 22. 需要驗證html樣式
- 23. 需要幫助jQuery驗證
- 24. 驗證是否需要TCP?
- 25. TypeError:LocalStrategy需要驗證回調
- 26. 407需要代理驗證
- 27. 需要驗證對話框
- 28. AngularJS下拉需要驗證
- 29. 驗證表單NG-需要
- 30. 需要驗證CRM憑據
是的,這將工作,但沒有辦法將其移入模型? – Gavin 2009-11-07 20:42:17
絕對。這只是一個irb會話;將其移入'Account.create_with_deposit!(attributes)'。 – 2009-11-08 15:50:06