说我在Rails 4中有Library
和Book
个模型。
我还有一个book.json.jbuilder文件,它定义了如何在json中呈现Book。
我如何告诉library.json.jbuilder重用book.json.jbuilder来渲染book json而不是复制代码?
#library.json.jbuilder example
json.(@libraries) do |library|
json.id library.id
json.name library.name
# instead of the line below, is it possible to tell jbuilder
# to render books using book.json.jbuilder?
json.books library.books, :title, :author
end
答案 0 :(得分:7)
这可以使用partials来实现。
请参阅下面的示例,其中包含_book.json.jbuilder和_library.json.jbuilder部分。
此处有更多文档:https://github.com/rails/jbuilder
# books/_book.json.jbuilder
json.id book.id
json.title book.title
json.author book.author
# books/index.json.jbuilder
json.array! @books, partial: 'books/book', as: :book
# libraries/_library.json.jbuilder
json.id library.id
json.title library.name
json.books library.books, partial: 'books/book', as: :book
# libraries/index.json.jbuilder
json.array! @libraries, partial: 'libraries/library', as: :library