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

后端 未结 2 1298
悲&欢浪女
悲&欢浪女 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:37

    There is a plugin that helps you with this for belongs_to associations: Validates existence of. But, maybe you can add your own validation? What about something like this:

    # Assuming your foreign key is user_id (which references the table User)
    validate :user_id_exists
    
    def user_id_exists
      return false if User.find_by_id(self.user_id).nil?
    end
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题