Question

I'm trying to put together an association that takes advantage of Mongo's document subkey indexing. For example, I have two collections, posts and topics. Posts have a tags key, which is an indexed set of tags for the post - pretty vanilla. What I want to do though, is have something in my Topic model like:

class Topic
  key :name, String
  many :posts, :query_conditions => {:tag => lambda {|i| i.name} }
end

The idea being that I have a Topic with a name of "mongomapper", when I invoke @topic.posts, I want the association to be executing the equivalent of:

post.find({tag: "mongomapper"})

I effectively need something like AR's finder_sql option (complete with the ability to interpolate per-instance values into the query), which I haven't been able to find in the MM association options yet. Does anything like that exist?

Was it helpful?

Solution

After digging through the MM internals, I decided this just wasn't going to happen. Specifically, has_many associations are always constrained by a :foreign_key => proxy_owner._id addition to the query; there's no way to avoid that criteria being added, which means that you can't set up associations with custom finders.

I just used a named scope on my Post model and a helper method on the Topic model.

class Post
  scope :tagged, lambda {|tag| where(:tags => tag)}
end

class Topic
  def posts
    Post.tagged(name.downcase)
  end
end

That returns a query proxy, so for all intents and purposes, I can treat it like an association for read-only purposes. Works well enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top