Dennis Hackethal
Dennis Hackethal

Reputation: 14275

Rails foreign key validations

I have a user and a document model; a user has many documents, a document belongs to a user. You can generalize this to just having a parent and a child model.

Now I am writing unit tests for the child model and I am wondering whether I have to validate the parent_id field, too (for example only_integer, greater than zero, that the id exists in the parent table, etc.) - or does Rails automatically do that for me since those are inherent foreign key attributes?

Upvotes: 3

Views: 394

Answers (2)

Matthias
Matthias

Reputation: 4375

Rails 3 way would be

# child.rb
validates :parent, presence: true

Upvotes: 5

MrDanA
MrDanA

Reputation: 11647

You can add foreign key constraints, even through Rails (i.e don't have to manually connect to your DB and execute raw SQL), but you can do it on the model itself as well:

# child.rb
validates_presence_of :parent

That will make sure that it has a parent_id and that that ID is found within the Parent table.

Otherwise, no, Rails does not automatically check constraints for you.

Upvotes: 3

Related Questions