引发错误,而不是重定向和刷新错误

时间:2018-09-07 00:01:51

标签: ruby-on-rails ruby-on-rails-5

当我填写表单验证错误时-会引发错误(如下屏幕所示),而不是重定向到 new_product_path 并刷新所有错误。如果我正确使用表单并通过所有验证,则可以正常工作,并将我重定向到 index 。另外,产品属具属:user和用户属具has_many:products。

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MinecraftClient
{
    class Utilities
    {
        private static Dictionary<string, string> whitelisted;

        static Utilities()
        {
            string json = File.ReadAllText("whitelists/walls.json");
            var data = JsonConvert.DeserializeObject<dynamic>(json);
            whitelisted = data.ToObject<Dictionary<string, string>>();
        }

        public static ulong GetWhitelisted(string key)
        {
            if (whitelisted.ContainsKey(MinecraftClient.ChatBots.WeeWoo.username))
            {
                ulong whitelistedid;
                bool parsed = UInt64.TryParse(key, out whitelistedid);
            }
            return 0;

        }
        public static ulong whitelistedid;
    }
}

控制器:

%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
      =@product.errors.full_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

enter image description here

1 个答案:

答案 0 :(得分: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