Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby on Rails | ルーティング | RESTfulインターフェースを定義

概要

RESTfulインターフェースを定義

詳細

RESTfulインターフェースを定義します。
RailsでRESTfulインターフェースを定義するにはroutes.rbで以下の記述をします。

routes :controller_name

上記の定義によって生成されるルーティングについてはサンプルを参照。
上記の定義によりlink_toで利用するUrlヘルパも自動生成されます。

path url return contents
controller_name_path controller_name_url /controller_name 一覧画面
controller_name_path(id) controller_name_url(id) /controller_name/:id 1件詳細画面
new_controller_name_path new_controller_name_url /controller_name/new 新規登録画面
edit_controller_name_path(id) edit_controller_name_url(id) /controller_name/:id/edit 編集画面

サンプル

controller
rails g controller index show new create edit update destroy
# Hoges
class HogesController < ApplicationController
  # index
  def index
    @hoges = Hoge.all
  end

  # show
  def show
    @hoge = Hoge.find params[:id]
  end

  # new
  def new
  end

  # create
  def create
    Hoge.create do |h|
      h.hige = params[:hige]
    end
    redirect_to :action=>'index'
  end

  # edit
  def edit
    @hoge = Hoge.find params[:id]
  end

  # update
  def update
    Hoge.update(hige: params[:hige])
    redirect_to :action=>'index'
  end

  # destroy
  def destroy
    Hoge.delete params[:id]
    redirect_to :action=>'index'
  end
end
index.html.haml
%h1 Hoges#index
%p Find me in app/views/hoges/index.html.haml
%hr/ 
= link_to "追加", new_hoge_path
%hr/ 
%table{style: "width:400px;"}
  %tr 
    %th url_helper
    %th url
  %tr
    %td 
      hoges_path
    %td 
      = hoges_path
  %tr
    %td 
      hoges_path(1)
    %td 
      = hoges_path(1)
  %tr
    %td 
      new_hoge_path
    %td 
      = new_hoge_path
  %tr
    %td 
      edit_hoge_path(1)
    %td 
      = edit_hoge_path(1)
%hr/ 
%table 
  %thead 
    %tr 
      %th buttons
      %th id
      %th name
  %tbody
    -@hoges.each do |h|
      %tr 
        %td 
          = link_to "詳細", hoge_path(h.id)
          = link_to "編集", edit_hoge_path(h.id)
          = link_to "削除", "/hoges/#{h.id}", method: :DELETE
        %td 
          = h.id
        %td 
          = h.hige
routes.rb
resources :hoges
ルーティングの確認
rake routes | grep hoges
               hoges GET    /hoges(.:format)                hoges#index
                     POST   /hoges(.:format)                hoges#create
            new_hoge GET    /hoges/new(.:format)            hoges#new
           edit_hoge GET    /hoges/:id/edit(.:format)       hoges#edit
                hoge GET    /hoges/:id(.:format)            hoges#show
                     PATCH  /hoges/:id(.:format)            hoges#update
                     PUT    /hoges/:id(.:format)            hoges#update
                     DELETE /hoges/:id(.:format)            hoges#destroy

画面

一覧画面

詳細画面

新規画面

編集画面