简体   繁体   English

Rails外键验证

[英]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? 现在我正在为子模型编写单元测试,我想知道是否还必须验证parent_id字段(例如only_integer,大于零,id存在于父表中,等等) - 或者是否自动执行Rails因为这些是固有的外键属性,所以对我来说呢?

Rails 3 way would be Rails 3方式将是

# child.rb
validates :parent, presence: true

You can add foreign key constraints, even through Rails (ie don't have to manually connect to your DB and execute raw SQL), but you can do it on the model itself as well: 您可以添加外键约束,即使通过Rails(即不必手动连接到您的数据库并执行原始SQL),但您也可以在模型本身上执行此操作:

# 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. 这样可以确保它具有parent_id,并且可以在Parent表中找到该ID。

Otherwise, no, Rails does not automatically check constraints for you. 否则,不,Rails不会自动检查您的约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM