LoginSignup
2
1

More than 3 years have passed since last update.

【Ruby on Rails】確認ページ作成

Posted at

目標

画面収録 2020-10-25 18.11.03.mov.gif

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

準備

今回はscaffoldを使用し、投稿の確認画面を作成します。

ターミナル
$ rails g scaffold post body:string
$ rails db:migrate

controllerの編集

下記を追加。

app/controllers/posts_controller.rb
def confirm
  @post = Post.new(post_params)
end

routeの編集

下記を追加

config/routes.rb
  resources :posts
  post 'posts/confirm', to: 'posts#confirm', as: 'confirm'

viewの編集

このままの状態であれば、new画面で投稿するとcreateアクションが実行され、保存されてしまいます。
したがって、new画面からはconfirmにparamsを飛ばすよう記述します。
<%= render 'form', post: @post %>を削除し、下記のように記述します。

app/viwes/posts/new.html.erb
<h1>New Post</h1>

<%= form_with(model: @post, local: true, url: confirm_path) do |form| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :body %>
    <%= form.text_field :body %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>


<%= link_to 'Back', posts_path %>

app/viwes/posts配下にconfirm.html.erbを作成します。
<%= @post.body %>で投稿内容を表示し、
<%= form.hidden_field :body %>でcreateアクションにparamsを渡しています。

app/viwes/posts/confirm.html.erb
<div>投稿内容確認<br><br>
  <%= @post.body %><br><br>
</div>
<%= form_with(model: @post, local: true) do |form| %>
  <div class="actions">
    <%= form.hidden_field :body %>
    <%= form.submit %>
  </div>
<% end %>

まとめ

投稿画面での確認画面はあまりないとは思いますが、
新規登録画面ではよく見る表示だと思いますので、
会員登録等の機能を実装するなら必須の機能です。

またtwitterではQiitaにはアップしていない技術や考え方もアップしていますので、
よければフォローして頂けると嬉しいです。
詳しくはこちら https://twitter.com/japwork

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