kaabashot
kaabashot

Reputation: 3

Correct way to generate idiomatic rails controller?

I'm learning rails 6 and walking through creating some toy resources. I know in my data model, I want to create a "widget" let's say, but I don't want everything that a scaffold is going to produce, so I'd like to manually generate everything that I know I'll need and nothing more. I started with a simple model. Next I'm trying to generate the controller + views I know I'll need. I ran:

rails g controller widgets index new show delete

This ended up creating a router with the following routes:

  get 'widgets/index'
  get 'widgets/new'
  get 'widgets/show'
  get 'widgets/delete'

I'm surprised by this, I would have expected something similar to the routes that are generated by default with the scaffold:

     things GET    /things(.:format)         
            POST   /things(.:format)         
  new_thing GET    /things/new(.:format)     
 edit_thing GET    /things/:id/edit(.:format)
      thing GET    /things/:id(.:format)     
            PATCH  /things/:id(.:format)     
            PUT    /things/:id(.:format)     
            DELETE /things/:id(.:format)     

Am I using the correct generator command to accomplish what I described? Or is this something that I would just need to manually set up with my routes?

EDIT: I realized the action I'm actually looking for is :destroy, and not :delete

Upvotes: 0

Views: 49

Answers (2)

Bouaik Lhoussaine
Bouaik Lhoussaine

Reputation: 584

This is normal if you don't want to use scaffold, and for some routes they are need to be setup manually like the delete route, it is a delete request not get like the controller is generating (the controller always generate get requests because it expects a corresponding view)

You can use: resources :widgets, only: [:index, :new, :show, :destroy]

this will generate what you want because this is the convention used in rails

Upvotes: 1

Eyeslandic
Eyeslandic

Reputation: 14910

The Rails generators are really just for generating the needed files, for anything out of the ordinary you will have to manually change things.

You can add this to your routes.rb instead of that list of GETs

resources :widgets, only: [:index, :new, :show, :destroy]

Which will produce an output similar to what you have in your question if you do rails routes from the terminal.

Upvotes: 0

Related Questions