Emulating ActiveRecord functionality (has_many :through relation)

51 views
Skip to first unread message

Matt Lightner

unread,
Oct 29, 2010, 9:35:24 PM10/29/10
to Mongoid, sc...@redradiant.com
Hey All,

Is there a "best practice" in Mongoid for dealing with what, in AR,
would be a has_many :through relationship?

We're using the Facebook API and, for instance, a photo has many tags,
and each tag links to a user (one of likely many users tagged in the
photo, each linked to the photo through a "tag").

What's the best way to represent this in Mongoid? In AR it would go
something like this:

class Photo << ActiveRecord::Base
has_many :tags
has_many :users, :through => :tags
end

class Tag << ActiveRecord::Base
belongs_to :user
end

I guess you could add a method to the Mongoid Photo document class
after defining the embeds_many :tags relation (on Photo) such as:

def users
tags.collect { |t| t.user rescue nil }
end

Is that the best way to deal with this type of relationship? Is there
a reason this functionality hasn't been built into the embeds_many
class macro yet? If I submitted a patch, would it be rejected for
some reason? Or is this just not the kind of relationship that
MongoDB was meant to handle? (My apologies in advance if this is a
wholly ill-conceived question.)

Thanks!
Matt

fuzzybunnies

unread,
Nov 1, 2010, 9:38:15 PM11/1/10
to Mongoid
What other data does your Tag model contain?
Reply all
Reply to author
Forward
0 new messages