Search code examples
ruby-on-railsjsonbuilder

sharing jsonbuilder files for index and show


Let's say I have a model called Customer. My index.json.jbuilder looks something like this

eg

json.array!(@customers) do |customer|
  json.extract! customer, :id, :name, :phone_number, :email
  # some more nested fields of customer
end

and my show.json.jbuilder also has similar duplicate code

json.extract! customer, :id, :name, :phone_number, :email
# some more nested fields of customer

is there a better way, say to include the show.json.jbuilder inside the index.json.jbuilder. I don't want duplicate the logic of rendering the json in two places.


Solution

  • Use partials (partial!) as described in jbuilder documentation.