我有以下型号:
我的问题是:我如何进行以下验证?
如果发票状态不是草稿:
现在我已经有了这个,但它没有用:
class Invoice < ActiveRecord::Base
has_many :invoice_lines
validates_associated :invoice_lines
end
class InvoiceLine < ActiveRecord::Base
belongs_to :invoice
validate :check_invoice_status
def check_invoice_status
unless self.invoice.draft?
errors.add_to_base "Can't add or modify: the invoice status is not draft"
end
end
end
由于validates_associated“allways failed”,因此无法正常工作;一旦发票状态更改为“已发送”,发票行始终无效。我只希望在“更新”或“添加新”时检查它们。
Thaks。
答案 0 :(得分:1)
使用“已更改?”发票行:
def validate_invoice_status
if changed? and !invoice.draft?
errors.add_to_base "Can't add or modify: the invoice status is not draft"
end
end
答案 1 :(得分:0)
试试这个:
def check_invoice_status
unless self.invoice.draft?
self.reload if changed? && !new_record?
errors.add_to_base("Can't add: the invoice status is not draft") if new_record?
end
end