mercredi 11 avril 2018

RoR Render errors partial if edit fails

the problem I have is probably easy to solve, although I did a lot of search and cant find a solution.

I have in my _errors.html.erb

<% if obj.errors.any? %>
 <div class="row">
  <div class="col-md-8 col-md-offset-2 col-xs-12">
   <div class="panel panel-danger">
    <div class="panel-heading">
      <h2 class="panel-title">
        <%= pluralize(obj.errors.count, "error") %>
        prohibided this form from being saved:
      </h2>
      <div class="panel-body">
        <ul>
          <% obj.errors.full_messages.each do |msg| %>
           <li><%= msg %></li>
          <% end %>
        </ul>
      </div>
    </div>
   </div>
  </div>
 </div>
<% end %>

Then I have in my edit.html.erb that has a form and:

<%= render 'layouts/errors', obj: @my_obj_here %>

Then in the controller update/create (lets use the update as example):

def update
    if @my_obj_here.update(params[:my_obj_here].permit(:body))
        redirect_to my_path_here_path(@my_obj_here), notice: "Something."
    else
        render 'edit'
    end
 end

The issue happens when I try to update and the submit info is invalid, which will fall into the "render 'edit'"

The errors show correctly (in this case max length 100) but my url changes from: my_obj_here/1/edit to my_obj_here/1

which should not happen.

So next I tried replacing the "render 'edit'" with "redirect_to :back" but this just ignores the <%= render 'layouts/errors', obj: @my_obj_here %> in the edit.html.erb.

Can someone help me out figuring out how to render the same my_obj_here/1/edit? I believe I need to use the "render" my method because the redirect will just skip the errors partial.

Also, in my update method you probably noticed this "if true": redirect_to my_path_here_path(@my_obj_here), notice: "Something." I could the the same and just change my code to: redirect_to :back, :notice => "something." This would work, but does not show the errors as I want them to shown when my the errors partial is used.

Aucun commentaire:

Enregistrer un commentaire