Search code examples
ruby-on-railssimple-form

Rails - Simple Form - style error messages


I'm trying to make a partial in my views folder, which his shared for error messages.

I want to remove the simple form standard error message and replace it with my own styling - across all models.

My question is, how do I reference the relevant model in my partial. Depending on where its used, it needs to reference the form in which the partial is included.

For example, the standard simple form error block is:

<% if @question.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@project_question.errors.count, "error") %> prohibited this question from being
        saved:</h2>

      <ul>
        <% @project_question.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
        <% end %>
      </ul>

How do I replace @question, with @[whatever the relevant model is called]?

Thank you


Solution

  • For this you can make a partial _error_messages,html.erb

    <% if model.errors.any? %>
      <div id="error_explanation">
        <h2>
          <%= pluralize(model.errors.count, "error") %> prohibited
           this from being saved:
        </h2>
        <ul>
          <% model.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
          <% end %>
        </ul>
      </div>    
    <% end %>
    

    And you can render this partial in your view as:

    <%= render partial: "error_messages", locals: {model: @question} %>