Ruby on rails 模型外键验证

Ruby on rails 模型外键验证,ruby-on-rails,validation,model,Ruby On Rails,Validation,Model,我有两种型号:客户机和发票。 每个客户可以有许多发票,每个发票只属于一个客户。如果客户被删除,与他相关的发票也应被删除 这都是通过以下代码完成的: #### Invoice class class Invoice < ActiveRecord::Base attr_accessible :amount, :body, :client_id, :filename, :subject validates :amount, :body, :client_id, :filename, :

我有两种型号:客户机和发票。 每个客户可以有许多发票,每个发票只属于一个客户。如果客户被删除,与他相关的发票也应被删除

这都是通过以下代码完成的:

#### 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
#####发票类
类发票true
验证:client_id,:numericality=>{:only_integer=>true,:大于或等于0}
属于:客户
结束
####客户端类
类Clienttrue
验证:zip,:numericality=>{:仅\u integer=>true,:大于或等于\u to=>10000,:小于或等于\u to=>99999}
有很多:发票,从属::销毁
结束
这就是我到目前为止构建的—但我想知道:当用户创建新发票时,如何验证客户机表中的客户机id是否确实存在,如果不存在,如何显示相应的错误消息?

对于外键(FK)约束,我建议您在数据库中这样做。 Rails本身对此没有内置支持。如果您确实想检查Ruby/Rails中是否存在外键,这会给应用程序增加不必要的负载

以下几个链接可能会有所帮助:


略微更新了答案;在Rails 4.2中,您可以对单一关联使用新的
required
选项

class Invoice < ActiveRecord::Base
  belongs_to :client, required: true
end

这是公关:

谢谢!这一切都是好的,我只需要告诉用户,id不存在,如果是这样的话。你会怎么做?在模型中有没有办法做到这一点?仅供参考,您的第一个链接现在已断开。
has_one :foo, required: true