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