当我重新渲染同一视图时,我的 Ruby on Rails 活动记录验证错误不会持续存在

问题描述 投票:0回答:1

我正在使用 Rails 7 和 Carrierwave 上传图像。

我的图像上传按预期工作,但当我尝试对不正确的文件类型实施验证错误消息时,出现了问题。在我的 app/uploaders/user_avatar_uploader.rb 文件中,我指定仅接受 jpeg、jpg 和 png 文件。

当我使用以下代码并使用 binding.pry 进行测试时(在尝试更新我的表单之后),我可以看到 @user_profile 对象上有 1 个错误。

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

但是,当我使用下面的代码修改更新方法并尝试在编辑视图中查看错误时,没有任何显示。需要明确的是,我正在尝试重新渲染最初显示的相同视图(编辑),并显示错误。

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

这是我在编辑视图中包含的代码,用于尝试显示错误。我的计数为“0”,并且在提交带有无效文件类型的载波上传表单后,它没有显示任何错误消息。

<%= @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 。在视图中,我没有看到任何错误。但是在控制台的 binding.pry 中,当我检查

@user_profile.errors.any?
时,我得到
true
并且可以看到错误。

<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 %>
ruby-on-rails activerecord error-handling carrierwave
1个回答
0
投票

我最终不得不禁用涡轮增压才能使其正常工作。我还将我的

form_for
重写为
form_with
,因为前者已被弃用。

新代码:

<%= form_with(model: @user_profile, data: { turbo: false }) do |f| %>
© www.soinside.com 2019 - 2024. All rights reserved.