检查关联是否存在而不会导致数据库命中 [英] Check if association exists without incurring a database hit

查看:74
本文介绍了检查关联是否存在而不会导致数据库命中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查ActiveRecord的 belongs_to 关联是否存在而不会引起数据库查询。

Is there a way to check if an ActiveRecord's belongs_to association exists without incurring a database query.

I 'm正在使用 example_association.present?进行检查,并导致该关联被加载。

I'm using example_association.present? to check and it results in the association being loaded if it does.

全部我想知道关联是否存在。

All I want to know is if the association exists.

推荐答案

您可以使用 reflect_on_all_associations as:

You could use reflect_on_all_associations as:

Foo.reflect_on_all_associations(:belongs_to).map(&:name).include?(:example_assoc)

其中:example_assoc belongs_to 关联。

或者如果您有模型类的实例:

Or if you have an instance of model class:

@foo.class.reflect_on_all_associations(:belongs_to).map(&:name).include?(:example_assoc)

这篇关于检查关联是否存在而不会导致数据库命中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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