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

后端 未结 1 1745
长发绾君心
长发绾君心 2021-02-13 00:59

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

1条回答
  •  遇见更好的自我
    2021-02-13 01:46

    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)
提交回复
热议问题