LoginSignup
2
2

More than 3 years have passed since last update.

railsでレコード登録前に確認画面を表示する

Posted at

はじめに

Ruby on Rails5 速習実践ガイドのアウトプットで投稿しています。
今回は、レコードの登録前に「こちらの内容で登録します」などの確認画面を表示する機能について投稿します!例として、タスク管理アプリケーションを作成しています。

目次

  1. アクションを作成する
  2. ルーティングの追加
  3. ビューの追加と編集
  4. 戻るボタンの実装
  5. 参考文献

アクションを作成する

まずは、確認画面に遷移するアクションをcontrollerに作成します。

app/controller/tasks_controller.rb
def confirm_new
  @task = current_user.tasks.new(task_params)
  render :new unless @task.valid?
end

ルーティングの追加

今回はタスクにネストさせるため以下のように設定します。

config/routes.rb
resources :tasks do
  post :confirm, action: :confirm_new, on: :new
end

この記述によって、/tasks/new/confirmというURLが生成されます。

ビューの追加と編集

追加

まず、確認画面のビューを作成します。

app/views/tasks/confirm_new.html.slim
h1 登録内容の確認

= form_with model: @task, local: true do |f|
  table.table.table-hover
    tbody
      tr
        th= Task.human_attribute_name(:name)
        td= @task.name
        = f.hidden_field :name
      tr
        th= Task.human_attribute_name(:description)
        td= simple_format(@task.description)
        = f.hidden_field :description
  = f.submit '戻る', name: 'back', class: 'btn btn-secondary mr-3'
  = f.submit '登録', class: 'btn btn-primary'

この画面を表示するタイミングでは、データは保存されていません。このあとにcreateメソッドを実行するときにデータが必要なので、hidden_fieldで前の画面のデータをユーザーからは見えないように保持して渡すようにしています。

編集

次に、新規追加画面の遷移先を確認画面に設定しておきます。

app/views/tasks/new.html.slim
= form_with model: @task, local: true, url: confirm_new_task_path do |f|
  .form-group
    = f.label :name
    = f.text_field :name, class: 'form-control', id: 'task-name'
  .form-group
    = f.label :description
    = f.text_area :description, rows: 5, class: 'form-control', id: 'task_description'
  = f.submit "確認", class: 'btn btn-primary'

戻るボタンの実装

確認画面の戻るボタンが押されたときの処理を実装していきます。先ほど作成した確認画面の戻るボタンには、name属性に「back」をつけています。このボタンを押したときにparams[:back]というパラメータが送られるので、このparamsがあれば、newメソッドにレンダーするという流れで実装します。

app/controllers/tasks_controller.rb
def create
    @task = current_user.tasks.new(task_params)
    if params[:back].present?
      render :new
      return
    end
    if @task.save
      redirect_to tasks_url
    else
      render :new
    end
  end

以上で、確認画面の実装は終了です!

参考文献

2
2
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
2
2