我有一個基本的發票設置與模型:發票,項目,LineItems。Rails 3:validates_presence_of驗證錯誤的默認值和相關模型
# invoice.rb
class Invoice < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
validates_presence_of :status
before_save :default_values
def default_values
self.status = 'sent' unless self.status
end
end
# item.rb
class Item < ActiveRecord::Base
has_many :line_items
validates_presence_of :name, :price
end
# line_item.rb
class LineItem < ActiveRecord::Base
belongs_to :item
belongs_to :invoice
before_save :default_values
validates_presence_of :invoice_id
validates :item_id, :presence => true
end
模型中有更多,但我只提出上述爲簡單。
我收到以下錯誤:
2 errors prohibited this invoice from being saved:
Line items invoice can't be blank
Status can't be blank
所以兩個問題:
如果我刪除
validates :invoice_id, :presence => true
我沒有得到Line items invoice can't be blank
錯誤信息了,但是爲什麼呢?我想驗證line_items上的invoice_id,所有line_items都應該有一個invoice_id。我如何驗證line_items上的invoice_id而不會出現錯誤?爲什麼我得到
Status can't be blank
錯誤,如果我將它設置爲默認值?我可以在invoices_controller上設置它,但我認爲應該在模型中設置默認值,對吧?我如何驗證狀態的存在並在模型中仍然具有默認值?