0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails勉強ネタ resources での名前付きヘルパー確認

Last updated at Posted at 2019-03-26

rails.png

普段何気なくroutes.rbにてresourcesメソッドを使用しているが、
色々確認してみる。

usersのコントローラーを作成(定番の7つのメソッド)

$ rails g controller users index new show create edit update destroy
users_controller.rb
class UsersController < ApplicationController
  def index
  end

  def new
  end

  def show
  end

  def create
  end

  def edit
  end

  def update
  end

  def destroy
  end
end
routes.rb
Rails.application.routes.draw do
  get 'users/index'
  get 'users/new'
  get 'users/show'
  get 'users/create'
  get 'users/edit'
  get 'users/update'
  get 'users/destroy'
end

この状態でrails routesを実行すると。

$ rails routes
       Prefix Verb URI Pattern              Controller#Action
  users_index GET  /users/index(.:format)   users#index
    users_new GET  /users/new(.:format)     users#new
   users_show GET  /users/show(.:format)    users#show
 users_create GET  /users/create(.:format)  users#create
   users_edit GET  /users/edit(.:format)    users#edit
 users_update GET  /users/update(.:format)  users#update
users_destroy GET  /users/destroy(.:format) users#destroy

全部users_'アクション名'という名前付きヘルパーになって、メソッドは全部GETです。
(空気を読んでPOSTとかDELETEなどになるのかと思っていた・・・)

resoureceメソッド使う

routes.rb
Rails.application.routes.draw do
  # get 'users/index'
  # get 'users/new'
  # get 'users/show'
  # get 'users/create'
  # get 'users/edit'
  # get 'users/update'
  # get 'users/destroy'

  resources :users
end

この状態でrails routes実行すると

$ rails routes
   Prefix Verb   URI Pattern               Controller#Action
    users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
     user GET    /users/:id(.:format)      users#show
          PATCH  /users/:id(.:format)      users#update
          PUT    /users/:id(.:format)      users#update
          DELETE /users/:id(.:format)      users#destroy

Restfulな形になった。
ニュアンス的にcreateuser_path のPOSTなイメージがあるが、
users_pathである事に注意(間違えそう)。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?