预期结果: 我在屏幕顶部看到错误,例如存在和长度验证错误
实际结果:
屏幕顶部没有错误,而我在日志中看到回滚。当我在创建操作中更改:redirect_to :back, alert: @reason.errors.full_messages
时,我确实看到顶部显示的错误。
情况:
items_controller
def show
@item = Item.find(params[:id])
@reason = Reason.new
@reasons = reasons_for_item(@item)
end
show.html.erb
<%= form_for(@reason, url: item_reasons_path(@item), html: { class: 'form-inline' }, remote: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label "Reason to use" %>
<%= f.text_field :body, class: 'form-control' %>
<%= f.button 'Submit', class: "btn", id: 'reason-submit-btn' %>
<% end %>
shared/_error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
reasons_controller
def create
@reason = Reason.new(reason_params)
@reason.user = current_user
@item = Item.find_by_id(params[:item_id])
@reason.item_id = @item.id
@reasons = reasons_for_item(@item)
if @reason.save
respond_to do |format|
format.html { redirect_to request.referer }
format.js
end
else
redirect_to :back
end
end
请告知
更新1:
而不是redirect_to
我将实现渲染,因为这会保留模型信息。错误仍未显示。
更新2: 通过将带有error_messages的表单添加到partial来修复它。现在,在保存失败后呈现部分。
答案 0 :(得分:1)
执行redirect_to
时,它会发送单独的请求,但不会存储当前状态,因此@reason
是一个没有错误的新实体。
您需要执行render
,而不是redirect_to
def create
@item = Item.find(params[:item_id])
@reason = @item.reasons.build(reason_params.merge(user: current_user))
@reasons = reasons_for_item(@item)
if @reason.save
respond_to do |format|
format.html { redirect_to request.referer }
format.js
end
else
render 'items/show'
end
end