Validations of associated has_many depending on status attribute (invoices and invoice lines)
I've got the following models:
- An Invoice has several statuses: Initially it's "draft", then it can be "sent", and "payed"
- An Invoice has_many InvoiceLines. InvoiceLines have a text an开发者_开发技巧d a cost.
My question is: How can I perform the following validations?
If the Invoice Status is not draft:
- No InvoiceLines can be added to it
- The values of the invoiceLines can't be modified
Right now I've got this, but it's not working:
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
This does not work as intented since the validates_associated "allways fails"; once the invoice status is changed to "sent", the invoice lines are allways invalid. I only want them to be checked if "updated" or "added new".
Thaks.
use "changed?" for invoice line:
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
try this:
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
精彩评论