LoginSignup
0
0

More than 3 years have passed since last update.

DHH流のルーティングに挑戦(初心者向け)

Last updated at Posted at 2019-05-04

 DHH流のルーティングに変更する

師匠にDHH流のルーティングを勧められたので、挑戦したら苦労したのでメモとして残します。

やりたいこと

Taskモデルの中に評価(evaluation)を書き込みたい。
今までのやり方は Tasksコントローラーの中に evalutaionアクションを追加する方法でしたが、「コントローラーのアクションはCRUDの限るべし」という DHH流のルーティングに変更してみました。

今までのやり方(アクションを増やしていく)

このやり方は間違いではないですが、アクションが増えて見通しが悪くなるので好ましくない。DHHが勧める方法に書き換えてみましょう。

app/controllers/tasks_controller.rb

class TasksController < ApplicationController
  def new
  end

  def create
  end

  def update
  end

  def evaluation
  end
end

DHH流のルーティング

config/routes.rb

resources :tasks do
  resource :evaluations, only: [:edit], module: 'tasks'
end

module: 'tasks' を記載することで、以下の RESTful なルーティングを得ることができます。

edit_task_evaluations GET    /tasks/:task_id/evaluations/edit(.:format)                                               tasks/evaluations#edit

app/controllers/tasks/evaluations_controller.rb

コントローラーは tasksディレクトリの中に作成します(ここで詰まっていた)。クラス名に Tasks:: が追加されている点にも注意。

class Tasks::EvaluationsController < ApplicationController
  def edit
    @task_id = params[:task_id]
    @task = Task.find(@task_id)
  end

  def update

  end
end

app/views/tasks/edit.html.erb

同じくビューも tasksディレクトリに入れてやります。(BootStrapを入れている)

<div class="row">
  <div class="col-md-6 offset-md-3">
    <h1>評価</h1>
    <%= "タスク番号#{@task_id}" %>
  </div>
</div>

以上でDHH流のルーティングは完成です。

呼び出し側

評価画面へのリンクはこのようになります。

@task = Task.find(params[:id])
redirect_to edit_task_evaluations_path(@task)

課題

苦労しましたが、DHH流のルーティングで見通しの良いプログラムを書くことができました。これからはなるべくこちらの書き方で統一していこうと思います。

課題としては、簡単なアクションも全て DHH流にするべきかの判定です。
例えば Taskモデルの canceled-> true にするだけのアクションまで別に分ける必要があるのでしょうか?

  def cancel
    @task = Task.find(params[:task_id])
    @task.update_attributes(canceled: true)
    redirect_to root_path, flash: { success: "タスクがキャンセルされました。" }
  end

間違っているところがあればコメントください。よろしくお願いいたします。

参考

ありがとうございます。
DHH流ルーティングの導入しようとした際にハマったこと
DHH流のルーティングで得られるメリットと、取り入れる上でのポイント

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