提升错误而不是重定向和闪存错误

问题描述 投票:0回答:1

当我填写表单验证错误时 - 它会引发错误(下面包含屏幕),而不是重定向到new_product_path并闪存所有错误。如果我正确使用表单并传递了所有验证,那么它可以正常工作,并将我重定向到索引。产品belongs_to:用户和用户has_many:产品。

%h1 Products
=form_with scope: :product, url: products_path, local: true do |p|
  -if @product.errors.any?
    =pluralize(@product.error.count, 'error')
    prohibited this product from being saved: 
    %ul
      [email protected]_messages.each do |msg|
        %li
          =msg
  %div
    =p.label :product_name
    %br
    =p.text_field :product_name
  %div
    =p.label :description
    %br
    =p.text_field :description
  %div
    =p.submit 'Create'

控制器:

class ProductsController < ApplicationController
  def index
  end

  def new
    @product = Product.new
  end

  def create
        @product = Product.create(product_params)

        if @product.save!
            flash[:notice] = "New product create"
            redirect_to products_index_path
        else
            flash.now[:alert] = "Something Gone wrong"
            render new_product_path
        end
  end

  def update
  end

  def delete
  end

    private
    def product_params
        params.require(:product).permit(:product_name, :description)
    end
end

模型:

class Product < ApplicationRecord
    belongs_to :user
    validates :product_name, uniqueness: true,
                    format: { with: /[A-Z]{3}[-][1-9]{3}/ }

    validates :description, presence: true,
                       length: { minimum: 5 }
end

enter image description here

ruby-on-rails ruby-on-rails-5
1个回答
0
投票

问题是@product.save!。我不得不使用save而不是save!

def create
  @product = Product.create(product_params)

  if @product.save     # <-- Here
    flash[:notice] = "New product create"
    redirect_to products_index_path
  else
    flash.now[:alert] = "Something Gone wrong"
    render new_product_path
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.