Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't "g controller" also create view file?

I've seen some Rails examples where generating a controller also creates the view file (not just the view folder).

In section 6.4 of Rails Guide, it shows an empty view folder and no view file. This is what my local installation is doing. I don't get any view files.

Is there some way to have Rails auto generate the view file when running rails g controller ...? Or, is it more likely the person created the view file manually and didn't show that part?

like image 338
4thSpace Avatar asked Jan 07 '23 05:01

4thSpace


1 Answers

Use rails generate scaffold instead which will generate the model, view and controller files for you in a single operation.

If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.

e.g.:

rails g scaffold Post name:string title:string content:text

But, if you really want to use rails g controller and also create the view files for you, then you have to specify the action names for your controller:

rails g controller Controllername index show edit update

This way, it will create the view files for these four actions: app/views/.../index.html.erb, app/views/.../edit.html.erb . . . etc.

But, looking at your case, you should use scaffolding as it will do a lot of work for you.

like image 196
K M Rakibul Islam Avatar answered Jan 17 '23 23:01

K M Rakibul Islam