I have two models: Client and Invoice.
Every client can have many invoices, every invoice belongs to only one client. If the client is deleted, the invoices with reference to him should be deleted, too.
This is all done through the following code:
#### 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
This is what I have built so far – but I am wondering: How can I validate that when a user creates a new invoice, the client id in the client table actually exists, and if not, display an according error message?
For foreign key (FK) constraints, I would recommend you do that in your database.
Rails itself has no built-in support for that. If you do want to check foreign keys’ existence in Ruby/Rails, that would add unnecessary load to the application.
Here are several links might help:
You Should Use Foreign Key Constraints in Rails
Support for foreign key constraint in Rails
Adding foreign key constraints in rails migrations