LoginSignup
24
16

More than 3 years have passed since last update.

field_with_errorsによるレイアウト崩れを防ぐ

Posted at

実装したいこと

新規会員登録機能バリデーションを設定し、入力項目にエラーがある場合はエラーメッセージとともに、入力ページに戻るように設定してします。
この時下の写真のようにレイアウト崩れが発生しますので、この事例について修正します。

初回入力時

スクリーンショット 2020-03-25 18.29.08.png

再入力時(レイアウト崩れ)スクリーンショット 2020-03-25 18.29.33.png

レイアウト崩れの原因

この事象の原因は、エラーが発生している時Railsが自動的にfield_with_errorsクラスを持つdivタグで、labelタグやinputタグを囲むことによって発生します。横並びになっている2つのinputタグそれぞれをdivダグで囲むため、改行されて表示されています。

new.html.haml
.contents-field
  = f.label :お名前(全角)
  %span.contents-field__require 必須
  %br
  = f.text_field :family_name, class:"contents-field__input half", placeholder:"例)山田"
  = f.text_field :first_name, class:"contents-field__input half", placeholder:"例)太郎"
.contents-field
  = f.label :お名前カナ(全角)
  %span.contents-field__require 必須
  %br
  = f.text_field :family_name_kana, class:"contents-field__input half", placeholder:"例)ヤマダ"
  = f.text_field :first_name_kana, class:"contents-field__input half", placeholder:"例)タロウ"

スクリーンショット 2020-03-25 18.30.26.png

解決方法

上記の事象に対する解決方法は2つが考えられます。

  • 自動で読み込まれるfield_with_errorsタグを読み込まないように設定する。
  • field_with_errorsに対してCSSをあてる

今回はfield_with_errorsタグを読み込まないようにする方法で、以下のようにapplicaton.rbを編集します。

applicaton.rb
module FreemarketSample65d
  class Application < Rails::Application
    #以下を追加
    config.action_view.field_error_proc = Proc.new { |html_tag, instance| html_tag }
  end
end

24
16
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
24
16