Rails - how do I validate existence of a row referenced by foreign key

后端 未结 2 1297
悲&欢浪女
悲&欢浪女 2021-02-13 00:52

Given that the \"Rails Way\" seems to be not to use foreign key constraints, I\'m looking for an alternative that will allow me to validate that the row a foreign key references

2条回答
  •  时光说笑
    2021-02-13 01:43

    Simply use like below,

    validates :user, presence: true
    

    It will automatically check the existence of user record in db.

    Reference from the Active Record Validation - presence:

    If you want to be sure that an association is present, you'll need to test whether the associated object itself is present, and not the foreign key used to map the association. This way, it is not only checked that the foreign key is not empty but also that the referenced object exists.

提交回复
热议问题