Say I have Library
and Book
models in Rails 4.
I also have a book.json.jbuilder file that defines how Book should be rendered in json.
How can I tell library.json.jbuilder to reuse book.json.jbuilder for rendering book json instead of duplicating the code?
#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
This can be achieved using partials.
See the example below with _book.json.jbuilder and a _library.json.jbuilder partials.
More documentation here: 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