我有此表单来创建和更新我的产品对象,但是我在获取错误消息时遇到了问题:
<%= simple_form_for @product do |f| %>
<% if @product.errors.any? %>
<div class="errors-container">
<ul>
<% @product.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.input :name, label: 'Product name' %>
<%= f.input :description, label: 'Description' %>
<%= f.association :category, label: 'Category' %>
<%= f.input :price, label: 'Price' %>
<%= f.input :picture %>
<%= f.input :picture_cache, as: :hidden %>
<%= f.button :submit %>
<% end %>
以及我的产品模型中的这些验证:
validates :name, :description, :category, :price, presence: true
这是我的控制器:
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
skip_before_action :authenticate_user!, only: [:index, :show]
def index
end
def show
end
def new
@product = Product.new
end
def edit
end
def create
@product = current_user.products.new(product_params)
if @product.save
respond_to do |format|
format.html { redirect_to products_path, notice: 'The product was successfully created.' }
end
else
redirect_to new_product_path
end
end
def update
@product.update(product_params)
respond_to do |format|
format.html { redirect_to product_path, notice: 'The product was successfully updated.' }
end
end
def destroy
@product.destroy
respond_to do |format|
format.html { redirect_to products_path, notice: 'The product was successfully destroyed.' }
end
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:name, :description, :category_id, :price, :picture, :picture_cache)
end
end
当我提交的表单中没有任何必填字段时,我不会收到任何错误消息。我在哪里做错了? 更新:我把我的控制器。
答案 0 :(得分:3)
由于您在create
上发生验证错误时进行重定向,因此@product
始终是Product
的新实例,甚至没有运行验证。
相反,您想呈现new
动作视图以再次显示该表单,但无需更改页面。这样@product
就会传递到视图以显示错误。
def create
@product = current_user.products.new(product_params)
if @product.save
respond_to do |format|
format.html { redirect_to products_path, notice: 'The product was successfully created.' }
end
else
# changed the following line
render :new
end
end