我正在运行Rails 6.0.2.1。
我在客户、发票和提案之间有一个相当简单的模型。发票属于提案(但这是可选的——发票不必基于提案)。此外,发票属于客户。
class Invoice < ActiveRecord::Base
belongs_to :client
belongs_to :proposal, foreign_key: "prop_id"
...
class Proposal < ActiveRecord::Base
belongs_to :client
has_one :invoice, foreign_key: "prop_id", dependent: :destroy
...
class Client < ActiveRecord::Base
has_many :proposals, dependent: :destroy
has_many :invoices, dependent: :destroy
...
这些模型彼此之间没有验证。也就是说,我没有验证表明发票必须有提案或客户。但是,如果我检查发票中任何字段的有效性,Rails会给我验证错误:
> inv = Invoice.new
=> #<Invoice id: nil, client_id: nil, prop_id: nil, tocb_id: nil, fromcb_id: nil,
date_invoice: "2020-02-10", written_by: nil, terms: nil, date_due: nil,
status: "Pending", shipping: nil, amount: 0.0, amt_due: 0.0, deposit: nil,
tax_rate: nil, comments: nil>
> inv.errors.count
=> 0
> inv.valid? :amount
=> false
> inv.errors.count
=> 2
> inv.errors
=> #<ActiveModel::Errors:0x000056466dac7a38 @base=#<Invoice id: nil, client_id: nil,
prop_id: nil, ... , @messages={:client=>["must exist"], :proposal=>["must exist"]},
@details={:client=>[{:error=>:blank}], :proposal=>[{:error=>:blank}]}>
为什么它会将缺少的客户和缺少的提案标记为存在错误?