LoginSignup
0
1

More than 3 years have passed since last update.

Railsチュートリアルの第7章のユーザー登録ページをbootstrap4とform_withで実装する。

Last updated at Posted at 2020-01-29

2020/02/01追記

タイトルどおりやっていきます。

使用している環境とgem

ruby 2.6.3
rails 5.1.6
bootstrap4

変更点

まずRailsチュートリアルのコードを見ましょう。

new.html.erb
| <h1>Users#new</h1> |
|:--|
|  |
| <div class="row"> |
|   <div class="col-md-6 col-md-offset-3"> |
|     <%= form_for(@user) do |f| %> |
|       <%= render 'shared/error_messages' %> |
|  |
|       <%= f.label :name %> |
|       <%= f.text_field :name, class: 'form-control' %> |
|  |
|       <%= f.label :email %> |
|       <%= f.email_field :email, class: 'form-control' %> |
|  |
|       <%= f.label :password %> |
|       <%= f.password_field :password, class: 'form-control' %> |
|  |
|       <%= f.label :password_confirmation, "Confirmation" %> |
|       <%= f.password_field :password_confirmation, class: 'form-control' %> |
|  |
|       <%= f.submit "Create my account", class: "btn btn-primary" %> |
|     <% end %> |
|   </div> |
| </div> |

こちらより引用

次に直したコードです。

new.html.erb
<h1>Sign up</h1>

<div class="row">
  <div class="col-md-6 offset-md-3"> //①

    <%= form_with model: @user, local: true do |f| %> //②
    <%= render 'shared/error_messages' %>

    <div class="form-group"> //③
      <%= f.label :name %>
      <%= f.text_field :name, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :email %>
      <%= f.email_field :email, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :password %>
      <%= f.password_field :password, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation, class: "form-control" %>
    </div>
    <div class="form-group text-center"> //④
      <%= f.submit "Create my account", class: "btn btn-primary" %>
    </div>
    <% end %>
  </div>
</div>

変更点は4つあり、コードに記してあります。

1.col-md-offset-3をoffset-md-3に変更
2.form_forをform_withに変更
3.form-groupでラベルと入力欄を囲む
4.text-centerをボタンに指定

では詳しく解説していきます。

1.col-md-offset-3をoffset-md-3に変更

bootstrap4ではcol-md-offset-をoffset-md-と書くようです。

2.form_forをform_withに変更

Rails5.1以降はform_forやform_tagはform-withと書くのが良いらしい。
form_with内で指定しているlocal: trueは非同期通信じゃなくてhtml使ったフォームの送信にしてねっこと。これがないと、アカウント作成しても「何も起きねえ.......」ってことになるので注意!

3.form-groupでラベルと入力欄を囲む

対応するタグと入力欄は正しく分けるためにclassでform-groupを指定してあげる。僕の場合は、これを指定しないとボタンがぐちゃぐちゃになりました。

4.text-centerをボタンに指定

ボタンを中央に寄せる

直した結果はこんな感じ

Screen Shot 2020-01-29 at 21.39.14.png

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