【问题标题】:Rails Mongoid includes doesn't load child modelsRails Mongoid 包含不加载子模型
【发布时间】:2014-06-11 00:07:24
【问题描述】:

我不知道它是否应该按我的预期工作,但我认为:

  def show
    render json: Book.includes(:genres).find(params[:id])
  end

应在图书模型中包含流派。

class Book
  include Mongoid::Document
  ...

  has_and_belongs_to_many :genres
end

class Genre
  include Mongoid::Document

  field :name, type: String
end

但在客户端中仅包含流派 ID 列表。

genre_ids: Array[1]
  0: Object
  $oid: "53532d3b616c6439c1070000"

我还用书尝试了另一个模型作者:

class Author
  include Mongoid::Document

  field :name, type: String

  has_many :books, inverse_of: :author
end

# in controller action

render json: Book.includes(:author).find(params[:id])

# returns =>
#    {"book":{"_id":{"$oid":"53532d3b616c6439c1140000"},"annotation":null,"author_id":{"$oid":"53532d3b616c6439c1000000"},"author_name":"Сомерсет Моэм","co_author_ids":[],"created_at":"2014-04-20T02:13:16.057Z","date":"1947","genre_ids":[{"$oid":"53532d3b616c6439c1070000"}],"html_path":"/Users/alder/Projects/pro_book_reader/rails-api/storage/GoCUMSZP/_.html","image_url":"GoCUMSZP.jpg","name":"Театр","toc_path":null,"token":"h9beplTN"}}

同样,它只返回$oidauthor_name 是图书模型属性)

那么,我可以用书籍模型加载所有类型的模型,而不需要额外的查询吗?

Rails 4.1,mongoid 4.0.0.beta1

我在流派模型中也没有关联,因为它会将所有书籍 ID 保存在流派模型中。

更新

Identity Map 已从 mongoid 4 中删除。有新的preload_models 选项,但当它为 true 时也不会加载流派。

附言

它适用于render json: {book: book, genres: book.genres},所以在includes 被修复之前可能没问题。

PS2

我想这includes 可能不是我想的。我的意思是,在您诉诸关系模型之后,避免额外的查询可能会有所帮助。而且它不会从所有孩子创建数组,或者将author 对象添加到作者字段(这是任何期望的,而不是无用的ID)。

【问题讨论】:

  • 也许我应该使用 jbuilder 来完成这项任务。
  • But on client in contains only list of genre ids. ?你能分享一下你试图显示一本书的相关类型的视图代码吗?
  • 我只是用 angularjs 得到 json 响应。我不认为前端代码是米特。当然,我可以在 json 中发送一个包含流派的数组,或者使用另一个查询从前端获取它。我希望流派已经包含在 json 中。否则,这个includes(:genres) 做了什么?也许这种情况下有急切的选择,或者其他什么。
  • 我需要sql模拟加入MongoDB的基础。
  • 在 mongoid 中有一个开放的错误可能有用github.com/mongoid/mongoid/issues/2041

标签: ruby-on-rails mongodb ruby-on-rails-4 include mongoid


【解决方案1】:

为所有可用的books 中的每一个显示genres

def show 
  books = Book.all 
  render json: books, include: :genres 
end

为特定的book 显示genres

def show 
  book = Book.find(params[:id]) 
  render json: book, include: :genres 
end

【讨论】:

    【解决方案2】:

    您必须在 mongoid.yml 中启用身份映射才能进行预加载

    identity_map_enabled: true
    

    在选项中。

    【讨论】:

    • 身份映射已在版本 4 中删除。
    【解决方案3】:

    身份映射一直是removed from mongoid master (mongoid4)。您可以查看已打开的问题以获取更多详细信息,https://github.com/mongoid/mongoid/issues/3406

    当身份映射被删除时,Major Changes (Backward Incompatible) 中也会显示 mongoid 4 更改日志。 https://github.com/mongoid/mongoid/blob/006063727efe08c7fc5f5c93ef60be23327af422/CHANGELOG.md.

    正如他们所建议的,Eager load 现在可以在没有身份映射的情况下工作。

    【讨论】:

    • 我知道,但不知道
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2018-09-15
    相关资源
    最近更新 更多