Dennis Hackethal
Dennis Hackethal

Reputation: 14295

Model foreign key validation

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?

Upvotes: 4

Views: 4956

Answers (2)

Dennis Hackethal
Dennis Hackethal

Reputation: 14295

Slightly updated answer; in Rails 4.2, you can make use of the new required option on singular associations.

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

Rails 4.2 also supports this on has_one associations:

has_one :foo, required: true

Here is the PR: https://github.com/rails/rails/pull/16056

Upvotes: 1

inntran
inntran

Reputation: 1033

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

Upvotes: 5

Related Questions