0

ページの複数のタブでエラーを表示するように設計変更を実装しようとしています。

私は自分のモデルをそのように検証してきました: (検証は他にもあります。これはほんの一例です。)

validate :has_comment? if: lambda { |r| r.last_step? && r.request_type == :snf_request }

def has_comment?
  errors[:base] << "Request must have at least one comment." if self.comments.blank?
end

これは機能しますが、明らかにこれらのエラー メッセージはすべてそのerrors[:base]配列に追加されます。

私はこのようなことをしてみました:

def has_comment?
  errors[:comments_page] << "Request must have at least one comment." if self.comments.blank?
end

エラー メッセージのパーシャルを呼び出して、エラーのsymbolどのページを出力するかを指定する a を渡すことができると考えました。

でこれをテストしたときrails console、新しい空のRequestオブジェクトを作成し、そのエラーを取得しました。入力r.errors[:base]すると、最初の例のように追加した検証メッセージとr.errors[:comments_page]、2 番目の例で追加したメッセージが表示されました。

ただし、アプリケーションにアクセスして実際に空白のリクエストを作成すると、これは機能しません。エラー メッセージは部分的にレンダリングされますが、空白です。これが私のパーシャルであり、参照用にレンダリングする方法です。

<%= form_for @request, html: { id: "new_request_form", autocomplete: :off } do |f| %>
  <%= render 'snf/shared/error_messages', target: f.object %>

そして部分:

<% if target.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-error">
      The form contains <%= pluralize(target.errors.count, "error") %>.
    </div>
    <ul>
      <% target.errors[:base].each do |msg| %>
        <li>* <%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

そして、ここにコントローラーアクションがあります

def update
  @request = Snf::Request.find(params[:id])
  @request.update_attributes(params[:snf_request])

  if params[:save] == "draft"
    @request.current_step = "draft"
  else
    @request.current_step = @request.steps.last
  end

  respond_to do |format|
    if @request.save
        if params[:save] == "draft"
          notice = 'snf.requests.message.draft'
        elsif is_new || is_forwarded
          notice = 'snf.requests.message.sent'
        else
          notice = 'snf.requests.message.updated'
        end

    format.html {
      flash[:notice] = I18n.t(notice)
      redirect_to snf_physician_path(current_user)
    }
    format.json {
    flash[:notice] = I18n.t(notice)
      redirect_to snf_physician_path(current_user)
    }
  else
    if params[:forwarded_consult_request]
      format.html {
        @request_types = Snf::RequestType.all
        @physicians = User.physicians_by_specialty
        render action: "forward"
      }
    else
      format.html{
        @request_types = Snf::RequestType.all
        @physicians = User.physicians_by_specialty
        render action: "edit_new"
      }
    end
  end
end

target.errors[:base]テストのためにそこに を追加しました。通常は と読みますtarget.errors.full_messages

ここで何か不足していますか?irb/rails consoleこれが機能しているように見えるのに、実際のアプリケーションに適用すると機能しないのはなぜですか? これを行う別のより健全な方法はありますか?

4

0 に答える 0