Ruby on rails 添加自定义验证后缺少模板错误,模板存在且未经验证即可工作

Ruby on rails 添加自定义验证后缺少模板错误,模板存在且未经验证即可工作,ruby-on-rails,validation,Ruby On Rails,Validation,这一个有点挑战性,所以请容忍我。以下是总结。我在我的一个模型中添加了自定义验证。在我添加这个之后,除了更新操作之外,所有操作都可以正常工作。如果我将新验证器限制为仅创建操作,那么更新操作可以正常工作。以下是相关代码: 在我的模型中 validate :start_must_be_before_end_time def start_must_be_before_end_time return if customer_start.blank? || customer_end.blank? if

这一个有点挑战性,所以请容忍我。以下是总结。我在我的一个模型中添加了自定义验证。在我添加这个之后,除了更新操作之外,所有操作都可以正常工作。如果我将新验证器限制为仅创建操作,那么更新操作可以正常工作。以下是相关代码:

在我的模型中

validate :start_must_be_before_end_time

def start_must_be_before_end_time
return if customer_start.blank? || customer_end.blank?

if customer_start > customer_end
 errors.add(:customer_start, "start time must be before end time")
end
end
在更新操作的我的控制器中:

def update
@handover = Handover.find(params[:id])
if @handover.update_attributes(params[:handover])
    UpdatedHandover.perform_async(@handover.id)
    flash[:success] = "Handover Template Updated and Approvals Sent!"
    redirect_to view_context.select_handover_cal(current_user)
  else
    flash[:error] = "Please correct the following errors in your form!"
    render edit_handover_path(@handover.id)
  end
end

因此,如果创建操作中的开始时间早于结束时间,则一切正常。它呈现新操作并显示错误。如果在更新操作中发生这种情况,则会为编辑操作提供缺少模板的错误。编辑文件位于正确的位置,如果验证器仅限于创建操作,则此操作有效。我一辈子都不明白为什么这会给我带来这么多麻烦。这是rails 3.2.18。谢谢你的帮助

应该将模板名称传递给render方法,而不是路径。因此,如果要呈现“edit.html.erb”,请传递“edit”

改变

 render edit_handover_path(@handover.id)


请注意,如果您在编辑模板中使用了额外的实例变量,则需要在更新操作中设置它们。

要更好地理解
渲染

使用
render
时,传递实例化对象(新创建或更新的)。尝试更新对象时,会触发验证,如果不成功,则渲染
edit
,因为内存中的对象包含必要的验证错误

但是当您使用
重定向到
时,会使用
编辑路径
。保存对象后,可以从数据库中获取持久化数据

您的问题可以通过两种方式解决:

render 'edit'
render :edit
# Your validation errors will persist


尝试更改渲染编辑交接路径(@handlover.id)以渲染“编辑”效果,现在我觉得自己很愚蠢;)如果你愿意回答,我会给你一个应得的问题:)谢谢你的帮助和解释@acezone98当你清楚一些事情时,你就会有信心。顺便说一句,在stackoverflow中有一个很好的方法来欣赏答案,我想你知道这一点。:)
render 'edit'
render :edit
# Your validation errors will persist
redirect_to edit_handover_path(@handover.id)
# Your validation errors will be gone