app/models/invoice_bar/invoice.rb in invoice_bar-0.0.6 vs app/models/invoice_bar/invoice.rb in invoice_bar-0.0.7

- old
+ new

@@ -1,51 +1,68 @@ -# encoding: utf-8 - module InvoiceBar class Invoice < ActiveRecord::Base before_validation :update_amount - + attr_accessible :number, :sent, :paid - + validates :number, presence: true validate :number_is_unique - + validates :due_date, presence: true include InvoiceBar::Billable::Base include InvoiceBar::Billable::StrictValidations include InvoiceBar::Billable::Invoicing - + include InvoiceBar::Billable::Associations::Base - include InvoiceBar::Billable::Associations::StrictValidations - + belongs_to :receipt - + include InvoiceBar::Billable::Filters - + + # This one is contact's address + has_one :address, + -> { where(addressable_type: "InvoiceBar::Invoice#contact_address") }, + class_name: InvoiceBar::Address, + foreign_key: :addressable_id, + foreign_type: :addressable_type, + dependent: :destroy, + required: true + has_many :items, as: :itemable, dependent: :destroy + accepts_nested_attributes_for :address, allow_destroy: true, reject_if: false + + has_one :user_address, + -> { where(addressable_type: "InvoiceBar::Invoice#user_address") }, + class_name: InvoiceBar::Address, + foreign_key: :addressable_id, + foreign_type: :addressable_type, + dependent: :destroy, + required: true + accepts_nested_attributes_for :user_address, allow_destroy: true, reject_if: false + # Search include InvoiceBar::Searchable - + def self.searchable_fields - ['number', 'contact_name', 'contact_ic'] + %w( number contact_name contact_tax_id ) end - + def mark_as_paid self.paid = true end - + def mark_as_sent self.sent = true end - + private - + # Validates uniqueness of a number for current user. def number_is_unique - invoices = Invoice.where(:number => self.number, :user_id => self.user_id) + invoices = Invoice.where(number: number, user_id: user_id) - if invoices.any? - errors.add(:number, :uniqueness) unless invoices.include? self + if invoices.any? && !invoices.include?(self) + errors.add(:number, :uniqueness) end end end -end \ No newline at end of file +end