【问题标题】:How can I expose a Mongoid embedded collection?如何公开 Mongoid 嵌入式集合?
【发布时间】:2011-08-20 22:21:49
【问题描述】:

我在我的 rails3 应用程序中设置了 mongoid,并创建了 2 个模型。 一个模型是用户,另一个模型是文章。

由于我每个用户都可以创建很多文章,所以我放了:

embedded_in :user

在 model/article.rb 文件中,并且:

embeds_many :articles

在模型/user.rb 文件中。

现在,如果我通过“app_url/articles/random_article_id”访问文章,我会收到以下错误。

Access to the collection for Article is not allowed since it is an embedded document, please access a collection from the root document.

虽然我想维持关系,但我希望任何人都可以访问文章。我该怎么做??

【问题讨论】:

    标签: ruby-on-rails mongoid database-relations


    【解决方案1】:

    另外,如果您确实需要嵌入文章,请执行以下操作:

    User.where("article.id" => params[:id].first.articles.find(params[:id])
    

    但是,正如 Ben 所说,您最好使用belongs_to 而不是embedded_in。

    【讨论】:

      【解决方案2】:

      听起来你想要的是引用关系而不是嵌入关系:http://mongoid.org/docs/relations/referenced.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多