我无法使验证错误起作用。我有一个创建产品页面,其中有两个 form_for,一个用于产品,一个用于照片。当产品未上传时,您会被发送到 redirect_to new_product_path
产品控制器
def new
@product = Product.new
@photo = Photo.new
end
def create
check_for_image = Photo.where(:product_id => nil, :user_id => current_user)
if check_for_images == []
redirect_to products_new_path, :notice => "Add an image then press start before submit"
else
@product = current_user.products.create(params[:product])
if @product.save
Photo.where(:product_id => nil, :user_id => current_user).update_all(:product_id => @product.id)
render "show", notice: "Product created!"
else
redirect_to new_product_path #, :flash => { :error => "Test!" }
# render "new"
end
end
end
我尝试渲染“新”而不是redirect_to,但我得到了NilClass:Class的未定义方法`model_name',错误指向照片表单
haml 创建产品页面
= form_for @photo, :html => { :multipart => true, :id => "fd" } do |f|
%span Add files...
= f.file_field :image
= form_for @product,:url => products_path, :html => { id: "fd", multipart: true } do |f|
- if @product.errors.any?
.error_messages
%h2 Form is invalid
%ul
- for message in @product.errors.full_messages
%li
= message
%p
= f.text_field :name, placeholder: "Name"
%p
= f.text_field :price, class: "auto", data: { a_sign: "$ " }, placeholder: "Price"
%p
= f.text_field :description, placeholder: "Description"
%p.button.start
= f.submit
产品型号
validates :user_id, presence: true
validates :name, presence: true, length: { minimum: 5 }
validates :price, presence: true, numericality: { greater_than_or_equal_to: 3.00 }