Rails-如何验证外键引用的行的存在 [英] Rails - how do I validate existence of a row referenced by foreign key

查看:53
本文介绍了Rails-如何验证外键引用的行的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于"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).

推荐答案

有一个插件可以帮助您解决 belongs_to 关联:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆