Rails Mongoid包含不加载子模型

时间:2014-04-25 10:22:13

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

我不知道它究竟应该如何运作我的期望与否,但我认为:

  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。

已更新

已从mongoid 4中移除了身份地图。有新的preload_models选项,但如果属实,它也不会加载类型。

PS

它与render json: {book: book, genres: book.genres}一起使用,所以在includes修复之前可能没问题。

PS2

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

3 个答案:

答案 0 :(得分:4)

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

identity_map_enabled: true
选项中的

答案 1 :(得分:3)

为所有可用的genres显示books

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

要显示特定genres的{​​{1}}:

book

答案 2 :(得分:0)

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

同样,mongoid 4更改日志显示在Major Changes (Backward Incompatible)中,因为身份地图已删除。 https://github.com/mongoid/mongoid/blob/006063727efe08c7fc5f5c93ef60be23327af422/CHANGELOG.md

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