LoginSignup
5
5

More than 3 years have passed since last update.

Railsのform_forで、bootstrap4を使ってフォームを横並びにする方法

Last updated at Posted at 2020-02-14

概要

Railsのform_forを使っている箇所で、フォームを横並びにするのに少しハマったので、共有させていただきます。

環境

ruby 2.6.3 Rails 5.1.6 bootstrap 4.4.1

方法

bootstrapのグリッドシステム(rowとcol-(数字))を使う。
フォームをdiv.rowで囲って、横並びにしたい要素をdiv.col-
で囲む。
(上記少し誤解を与える表現ですが、下記注意点をご参照ください)

注意点

form_forメソッドの外側でなく、内側にdiv.rowを配置する。

具体的な方法(OKパターン)

home.html.erb
<%= form_for(:session, url: login_path) do |f| %>        
  <div class="row">
    <div class="col-2">
      <div class="form-group">            
        <%= f.label :email %>
        <%= f.email_field :email, class: 'form-control' %>          
      </div>
    </div>
    <div class="col-2">
      <div class="form-group">            
        <%= f.label :password %>
        <%= f.password_field :password, class: 'form-control' %>
      </div>  
    </div>
    <div class="col-2 align-self-end">
      <div class="form-group">        
        <%= f.submit "ログイン", class: 'btn btn-primary' %>
      </div>
    </div>
  </div>
<% end %>

スクリーンショット 2020-02-14 10.38.23.png

ダメなパターン

home.html.erb
<div class="row">
  <%= form_for(:session, url: login_path) do |f| %>        
    <div class="col-2">
      <div class="form-group">            
        <%= f.label :email %>
        <%= f.email_field :email, class: 'form-control' %>          
      </div>
    </div>
    <div class="col-2">
      <div class="form-group">            
        <%= f.label :password %>
        <%= f.password_field :password, class: 'form-control' %>
      </div>  
    </div>
    <div class="col-2 align-self-end">
      <div class="form-group">        
        <%= f.submit "ログイン", class: 'btn btn-primary' %>
      </div>
    </div>  
  <% end %>
</div>

スクリーンショット 2020-02-14 10.51.33.png

以上です。

その他

Qiitaにちゃんとした(ちゃんとしてますか!?)投稿をするのが初めてでした。
ご指摘あればぜひお願いいたします。

5
5
1

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