I’m working on the Rails guide now and am confused about the controller and scaffold. In the guide I saw two commands:
$ rails generate controller home index
$ rails generate scaffold Post name:string title:string content:text
I know the first line means it creates a home controller with an action index. However, I don’t quite understand what the practical meaning is here. Does it simply mean it will render a page with an address “home/index”?
For the second line, what I understand is it creates an app called Post with three parameters name, title, and content. I don’t know if it is correct and am wondering what scaffold actually means. The guide’s explanation is a bit ambiguous to me.
Thanks.
So, first, you should just run them. They’ll list the files they create and you can look at them.
The first one creates a controller named
home(a piece of code for responding to web requests) with one action namedindex. An action is the combination of ant HTTP verb and a URL (in this case GET/home/index) that corresponds to a method in the controller. The generator also creates a dummy view for rendering that action, and some empty test and helper files. You can see that in what it prints:Particularly useful is the controller:
You haven’t given Rails any information about what you want that action to do (you just said, “create a controller called ‘home’ with some action called ‘index'”), so it’s up to you to fill out that method. And you can see the URL info by invoking
rake routes:In other words, when you send a GET request to
/home/indexit callsHomeController#index. Since that method is empty and doesn’t tell Rails what to render, it will default to rendering the view atapp/views/home/index.html.erb, which the generator also created and expects you to do something interesting with.The second generator does a lot more. It creates a resource, which means a model that you store in the database and also a controller with simple CRUD actions and dummy views to manipulate that model. So in addition to the controller/view stuff above, it also creates an upgrade script to create the right table in the DB and a Ruby class that will serve as the model. Look particularly at the first two “create” items here, and load them up in your editor:
You can see all the actions you can actually do, again by running
rake routes:Finally, check out the controller code at
app/controllers/PostsController.rbto see what these actions actually do (they’re a bit more interesting).