简体   繁体   English

Rails确定关联是否为has_one或has_many

[英]Rails determine if association is has_one or has_many

Wondering if there is an easy way to determine dynamically if a model's association is a " has_one " or " has_many " relationship (ie is this an association to one object or many). 想知道是否有一种简单的方法可以动态确定模型的关联是否为“ has_one ”或“ has_many ”关系(即这是一个对象或多个对象的关联)。

I'm using MongoMapper, so I am able to check if a class klass has an associated model assoc with a one or many relationship via 我使用的是MongoMapper,所以我能够检查如果一个类klass有一个相关的模型assoc通过一个或一对多的关系

klass.associations[:assoc].is_a? MongoMapper::Plugins::Associations::OneAssociation
klass.associations[:assoc].is_a? MongoMapper::Plugins::Associations::ManyAssociation

but this seems rather clunky, and isn't generic (ie won't work for ActiveRecord associations as well). 但这看起来相当笨重,并不是通用的(即不适用于ActiveRecord关联)。 I'd also like to avoid loading any objects, so I'm pretty sure that instance.assoc.is_a? Array 我也想避免加载任何对象,所以我很确定instance.assoc.is_a? Array instance.assoc.is_a? Array is out too. instance.assoc.is_a? Array也出来了。

Any ideas? 有任何想法吗?

UPDATE: So, I happened upon the Reflections Class methods http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html 更新:所以,我碰巧使用了反思类方法http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html

You can get all the has_many , belongs_to , etc. with reflect_on_all_associations method. 您可以使用reflect_on_all_associations方法获取所有has_manybelongs_to等。 It's all in there. 一切都在那里。 Or you can put in an association into reflect_on_association and it will tell you if it is a has_many , has_one , etc. Specifically: 或者你可以将一个关联放入reflect_on_association ,它会告诉你它是否是has_manyhas_one等。具体来说:

Model.reflect_on_association(:assoc).macro

This should be sufficient for all cases. 这应该适用于所有情况。 It doesn't actually solve the problem I'm currently working on, but it should solve this. 它实际上并没有解决我目前正在处理的问题,但它应该解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM