How to set up MongoMapper associations with complex conditions?
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} }开发者_如何学JAVA
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?
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.
精彩评论