Search code examples
ruby-on-railsactiverecorderror-handlingcarrierwave

My Ruby on Rails active record validation error does not persist when I re-render the same view


I'm using Rails 7 and Carrierwave to upload images.

My image uploading is working as expected, but my issue is happening when I try to implement validation error message for an incorrect file type. In my app/uploaders/user_avatar_uploader.rb file I specify to only accept jpeg, jpg and png files.

When I use the following code and test with binding.pry (after trying to update my form), I can see that there is 1 error on the @user_profile object.

def edit
        @user_profile = UserProfile.find(params[:id])
    end

    def update
        @user_profile = UserProfile.find(params[:id])
        if @user_profile.update(user_profile_params)
            redirect_to root_path
        else
            binding.pry
        end
    end

However, when I revise the update method with the code below and I try and see the errors in my edit view, nothing shows up. To be clear, I'm trying to re-render the same view (edit) that was originally showing, and show the errors.

def update
        @user_profile = UserProfile.find(params[:id])
        if @user_profile.update(user_profile_params)
            redirect_to root_path
        else
            render 'edit'
        end
    end

Here is the code I've included in my my edit view to try and show the errors. I'm getting '0' for the count and it's not showing any error messages after submitting the form with an invalid file type for the carrierwave upload.

<%= @user_profile.errors.count %>

    <% if @user_profile.errors.any? %>
      <h3>Some errors were found:</h3>
      <ul>
        <% @user_profile.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    <% end %>

Any idea what could be happening? I know the errors are there when my update controller action fires, but for some reason they're not being carried over to the render of my 'edit' view.

EDIT

I added the binding.pry directly in my view, after the code where I'm checking if there are any errors in the view. In the view, I'm not seeing any errors. But in the binding.pry in the console when I check @user_profile.errors.any? I get true and can see the error.

<h3>Profile</h3>

<%= @user_profile.errors.count %>

<% if @user_profile.errors.any? %>
  <h3>Some errors were found:</h3>
  <ul>
    <% @user_profile.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
  </ul>
<% end %>

<% binding.pry %>

Solution

  • I ended up having to disable turbo to get this to work properly. I also rewrote my form_for to a form_with since the former is being deprecated.

    New code:

    <%= form_with(model: @user_profile, data: { turbo: false }) do |f| %>