Home > OS >  Mongoid equivalent of ActiveRecord's "collection?" method for relations
Mongoid equivalent of ActiveRecord's "collection?" method for relations

Time:11-04

I am using Mongoid and trying to do something similar to ActiveRecord's collection? method.

I have a method that gets the relations from a class like:

def relations
  object.class.relations
end

This makes a hash of the relation objects.

Then in another method I am doing this:

if relations[key].collection?
   do stuff...
else
   do something else...
end

collection? isn't a method in this situation like it is in ActiveRecord. So I get

undefined method `collection?' for #<Mongoid::Association::Referenced::BelongsTo:0x00007feed3b61240>

What is the Mongoid way of doing this type of conditional?

CodePudding user response:

I'm assuming the method you're talking about it this one, which seems like it just returns true on has_many and HABTM associations... As of 8.0 we have the many? method to check if its HasMany or and EmbedsMany, but I don't think that is quite what you need. I can suggest a method for right now, and I will open a ticket to see if we can have this added:

def collection?(association)
  [
    Mongoid::Association::Referenced::HasMany, 
    Mongoid::Association::Referenced::HasAndBelongsToMany
  ].any? { |r| association.is_a?(r) }
end

EDIT: You can track this issue here.

  • Related