如何建立具有复杂条件的MongoMapper关联?

发布于 2024-09-14 03:51:08 字数 451 浏览 3 评论 0原文

我正在尝试建立一个利用 Mongo 文档子键索引的关联。例如,我有两个集合,帖子和主题。帖子有一个标签键,它是帖子的一组索引标签 - 非常普通。不过,我想做的是在我的主题模型中添加一些内容,例如:

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

这个想法是我有一个名为“mongomapper”的主题,当我调用@topic.posts时,我希望关联执行相当于:

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

我实际上需要诸如 AR 的 finder_sql 选项之类的东西(能够将每个实例的值插入到查询中),但我尚未在 MM 关联选项中找到它。有这样的东西存在吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸢与 2024-09-21 03:51:08

在深入研究了 MM 的内部结构之后,我决定这不会发生。具体来说,has_many 关联始终受到 :foreign_key => 的约束。 proxy_owner._id 除了查询之外;无法避免添加该条件,这意味着您无法与自定义查找器建立关联。

我只是在 Post 模型上使用了命名范围,并在 Topic 模型上使用了辅助方法。

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

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

它返回一个查询代理,因此出于所有意图和目的,我可以将其视为用于只读目的的关联。效果很好。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文