是否可以在没有新方法的情况下进行模型错误报告?据我了解,当您要报告错误时,您将创建以下控制器代码:
def new
@product = Product.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @product }
end
end
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render json: @product, status: :created, location: @product }
else
format.html { render action: "new" }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
然后您将创建一个包含以下代码的表单:
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
但是,您能否仅在控制器中使用“创建”方法来复制此技术?例如,使用 form_tag 将数据传递给“create”方法。也许是这样的:
'post', :class => 'form-horizontal', :style => 'text-align:center') 做 %> <% unless @product.blank? %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% end %>
<%= text_area_tag :content, '', :placeholder => 'Ask your classmates anything...' %>
<%= hidden_field_tag :user_id, current_user.id %>
<%= submit_tag 'Post', :class => "btn btn-medium btn-primary post-room-button" %>
<% end %>
I have been trying to do this, but I cannot find a way to get it to work. Whenever I submit the form that fails one of the validations in my model, the page simply redirects to my 'else' path in my respond_to
function in my create controller.