提问人:Tony M 提问时间:9/27/2023 最后编辑:Tony M 更新时间:9/28/2023 访问量:57
当我重新渲染相同的视图时,我的 Ruby on Rails 活动记录验证错误不会持续存在
My Ruby on Rails active record validation error does not persist when I re-render the same view
问:
我正在使用 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 %>
答:
0赞
Tony M
9/28/2023
#1
我最终不得不禁用涡轮增压器才能使其正常工作。我还重写了我的 a,因为前者正在被弃用。form_for
form_with
新代码:
<%= form_with(model: @user_profile, data: { turbo: false }) do |f| %>
评论
@user_profile
@user_profile
binding.pry
render 'edit'