Mongoid中ActiveRecord collection?方法的等效实现方式
在Mongoid中实现类似ActiveRecord的collection?判断功能
你可以通过两种方式判断Mongoid关联是否为集合类型(对应ActiveRecord的collection?):
方式一:判断关联对象的类型
Mongoid中集合类型的关联对应特定类,比如has_many对应Mongoid::Association::Referenced::HasMany,embeds_many对应Mongoid::Association::Embedded::EmbedsMany,has_and_belongs_to_many对应Mongoid::Association::Referenced::HasAndBelongsToMany。直接判断关联对象是否属于这些类即可:
def collection_association?(association) association.is_a?(Mongoid::Association::Referenced::HasMany) || association.is_a?(Mongoid::Association::Embedded::EmbedsMany) || association.is_a?(Mongoid::Association::Referenced::HasAndBelongsToMany) end # 使用示例 if collection_association?(relations[key]) # 处理集合关联的逻辑 else # 处理单对象关联(如belongs_to、embeds_one)的逻辑 end
方式二:通过关联的macro属性判断
所有Mongoid关联对象都有macro方法,返回定义关联时使用的符号(比如belongs_to返回:belongs_to,has_many返回:has_many)。只需判断该符号是否属于集合类型关联的标识:
def collection_association?(association) [:has_many, :embeds_many, :has_and_belongs_to_many].include?(association.macro) end # 使用示例 if collection_association?(relations[key]) # do stuff... else # do something else... end
这种方式更简洁,无需记忆具体的关联类名,推荐使用。
内容的提问来源于stack exchange,提问作者don_Bigote
相关产品推荐
相关产品推荐

