0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

バリデーションメッセージを Decorator で加工する

Posted at

のっぴきならない事情があり、フォームの入力パターンに応じて、バリデーションメッセージを生成後に加工したかったのでメモ。
例えば、下記のようなフォームがあったとする。

new.slim
= form_for post_form, url: confirm_post_path do |f|
  - if post_form.errors.present?
    ul
      - post_form.errors.full_messages.each do |msg| 
        li = msg

しかし、フォーム内の特定の選択肢を選んだ場合に、バリデーションメッセージを変えるという要件が加わったとする。
この場合、errors.full_messages は Array なので、Decorator で中身を1件ずつチェックして力技で置換した。

new.slim
= form_for post_form, url: confirm_post_path do |f|
  - post_form_decorator = ::PostFormDecorator.new(f.object)
  - if post_form.errors.present?
    ul
      - post_form_decorator.post_error_display(post_form.errors.full_messages).each do |msg|
        li = msg
post_form_decorator.rb
class PostFormDecorator
  delegate_missing_to :@post_form

  def initialize(post_form)
    @post_form = post_form
  end

  def post_error_display(error_full_messages)
    error_full_messages.each do |msg|
      if @post_form.category == 'music'
        msg.gsub!(/#{@post_form.model.class.human_attribute_name(:author)}/, '歌手')
      end
    end
  end
end

破壊的メソッドで中身を入れ替えているので、「!」を付けなければgsubで置換されないので注意。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?