Rails-如何验证外键引用的行的存在 [英] Rails - how do I validate existence of a row referenced by foreign key
问题描述
鉴于"Rails Way"似乎不是在使用外键约束,因此我正在寻找一种替代方法,该方法将允许我在保存A之前验证TableA中确实存在外键引用的行. TableB中带有table_a_id的对象.
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 does in fact exist in TableA before I save an object in TableB with table_a_id.
到目前为止,我发现执行此操作的唯一资源(找不到指向其中提到的博客文章的链接,该博客文章的日期为2007年)似乎与Rails 3.2不兼容,因此任何人都可以建议这样做一种方法吗?
The only resource I've found to do this so far (can't find a link to the blog post it was mentioned in, was dated 2007) doesn't appear to be compatible with Rails 3.2, so can anyone suggest a way of doing this?
我目前正在考虑创建一个验证器,以手动分配给模型中的相关属性,但是我不知道如何使用validate_each(object,attribute,value)来做到这一点.
I'm currently looking at creating a validator to manually assign to the relevant attributes in my models, but I can't work out how to do it with validate_each(object, attribute, value).
推荐答案
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
这篇关于Rails-如何验证外键引用的行的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!