如何使用Rails form_with (带有Ajax的远程表单)帮助器显示错误?
我有此代码:
def create
@incoming_package = IncomingPackage.new(tracking: params[:tracking])
if @incoming_package.save
redirect_to admin_incoming_packages_path, notice: "created"
else
flash.now[:danger] = "error" # not displayed
end
end
这是我的表格:
<%= form_with url: admin_incoming_packages_path do |form| %>
<%= form.text_field :tracking, required: true, autofocus: true, autocomplete: :off %>
<%= form.submit "Add" %>
<% end %>
如果没有错误,rails-ujs + Turbolinks可以正常工作,并且会在页面上自动添加新软件包。 如果程序包保存失败,如何显示错误(或其他内容)?
答案 0 :(得分:1)
这是一种入门的简单方法:
在表单的查看页面上:
<% if @incoming_package.errors.any?
<ul>
<% @incoming_package.errors.each do |error| %>
<li><%=error.full_messages%></li>
<% end %>
</ul>
<% end %>
然后在您的create
动作中执行以下操作:
def create
@incoming_package = IncomingPackage.new(tracking: params[:tracking])
respond_to do |format|
if @incoming_package.save
flash[:success] = "The package was saved."
format.html { redirect_to admin_incoming_packages_path, notice: "created" }
format.json { render json: {success: true}
else
@errors = @incoming_package.errors.add(:base, "Some custom message here if you like")
flash.now[:danger] = "error" # not displayed
format.html { render 'new' }
format.json { render json: @incoming_package.errors, status: :unprocessable_entity }
end
end
end
您还必须确保您的new
操作具有以下作用:
@incoming_package = IncomingPackage.new
答案 1 :(得分:-1)
如果您想检查任何错误,ruby都会提供一种非常简单的方法
@incoming_packages.errors.full_messages
将显示与模型有关的所有错误。您还可以与所有这些错误进行交互
`<%if @incoming_packages.errors.any?%>
<% @incoming_packages.errors.full_messages.each do |message| %>
<%= message %>
<%end%>
<%end%>`