0
0

More than 3 years have passed since last update.

field_error_procで[Rails/OutputSafety]を回避

Last updated at Posted at 2019-12-13

field_with_errorsをカスタマイズしたい

アプリ全体に適用する

config/application.rb
    config.action_view.field_error_proc = Proc.new do |html_tag, instance|
      %Q(<span class="has-error">#{html_tag}</span>).html_safe
    end

参考 : Railsのバリデーションエラーで、「field_with_errors」によるレイアウト崩れを防ぐ

ページ単位

app/hoge_helper.rbあたりに書く。

app/hoge_helper.rb
module SportsHelper
  ActionView::Base.field_error_proc = proc do |html_tag|
    %(<span class="has-error">#{html_tag}</span>).html_safe
  end
end

ただしこれだと、html_safeは使うなとRuboCopに怒られる。

RuboCop: Tagging a string as html safe may be a security risk. [Rails/OutputSafety]

[Rails/OutputSafety]を回避する書き方

app/hoge_helper.rb
module SportsHelper
  ActionView::Base.field_error_proc = proc do |html_tag|
    v = ActionView::Base.new
    v.content_tag(:span, html_tag, class: 'has-error')
  end
end

参考 : Railsでformのfield毎にエラーメッセージを表示させる便利設定

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