【发布时间】: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"}}
同样,它只返回$oid(author_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