33
votes

I've generated a new rails 4 (rc1) project using rails new and generated a scaffold using rails g scaffold.

As expected it has created the migration, controller and all required view files.

It has also created show.json.jbuilder and index.json.jbuilder.

I assume this is to aid json generation from models. The controller contains format.json invocations as well.

Question: why does it require json and which part of the generated application is using json? It doesn't look like (for me) the views are using json to render anything, seems they are rendered on the server side (@model variables are used in the views to get the content).

The edge guides (http://edgeguides.rubyonrails.org/) don't see to mention jbuilder and why it's needed there.

Thanks in advance! Please let me know if I can clarify the question.

4

4 Answers

34
votes

To answer the "why" part:

The relevance of scaffolding in Rails has somewhat shifted over the years. It is no longer meant to generate necessary code which couldn't be abstracted away easily. Today it is mostly an educational tool to provide you with a somewhat dynamic example and demonstrate best practices. (That's also the reason why they are sprinkled with comments with disputable usefulness)

In other words the generated files are meant to tell you:

If you are going to use Rails, here is a good way how you could do it.

or in your specific case:

If you are going to use JBuilder, here is a good way to generate JSON.

They are not meant to tell: "This is how it must be done." or "You have to keep all the generated stuff because it's necessary."

19
votes

As said before, Rails 4 seems to generate the files as a way to have a template for responding to a JSON query. So let's say you have "scaffolded" a model Car, then it will respond with a HTML page and a detail view of car (id 1) if you go /car/1.

Then if you go to /car/1.json, it will render the show.json.jbuilder file. There also seems to be some kind of automatic mechanism as the show method is empty when scaffolding:

def show
end
14
votes

Rails 4 scaffold generator creates jbuilder files because the gem 'Jbuilder' is in the Gemfile. If you remove this from your Gemfile this functionality will stop.

10
votes

Jbuilder gem included in RoR 4 by default. You could read about it on its page. There is a cast about it: Railscasts #320.