我不知道它是否应该像我期望的那样工作,但我认为:
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
但在客户端上,in 仅包含流派 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
不是我想的。我的意思是,在您诉诸关系模型后,这可能有助于避免额外的查询。它不会从所有 child 创建数组,或将 author
对象添加到 author 字段(这是任何人所期望的,而不是无用的 ID
)。
最佳答案
显示所有可用书籍
的流派
:
def show
books = Book.all
render json: books, include: :genres
end
显示特定书籍
的流派
:
def show
book = Book.find(params[:id])
render json: book, include: :genres
end
关于ruby-on-rails - Rails Mongoid 包含不加载子模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23290360/