我有两个模型:客户和发票。每个客户可以有很多张发票,每张发票只属于一个客户。如果客户被删除,与他相关的发票也应该被删除。
这一切都是通过以下代码完成的:
#### Invoice class
class Invoice < ActiveRecord::Base
attr_accessible :amount, :body, :client_id, :filename, :subject
validates :amount, :body, :client_id, :filename, :subject, :presence => true
validates :client_id, :numericality => { :only_integer => true, :greater_than_or_equal_to => 0 }
belongs_to :client
end
#### Client class
class Client < ActiveRecord::Base
attr_accessible :city, :country, :name, :street, :zip
validates :city, :country, :name, :street, :zip, :presence => true
validates :zip, :numericality => { :only_integer => true, :greater_than_or_equal_to => 10000, :less_than_or_equal_to => 99999 }
has_many :invoices, dependent: :destroy
end
这是我到目前为止所构建的 - 但我想知道:我如何验证当用户创建新发票时,客户端表中的客户端 ID 确实存在,如果不存在,则显示相应的错误消息?