我的.valid有效吗?正在阻止我的通知警报?

时间:2019-01-15 19:39:55

标签: ruby-on-rails ruby

问题:我的特定控制器的通知没有出现。

这不是布局,因为它可以在其他地方与其他使用它的控制器一起使用。

这是创建方法:

  def create
    @order = Order.new(order_params)
    @listing = Listing.find(params[:listing_id])
    @seller = @listing.user

    ....  
    ....
    ....

        if @order.valid?
          begin
            #stripe_charge_code_is_here

          rescue #stripe_error
             #code
          end
          if #code
             #flash[:error]
             #redirect_to
          else


        # respond_to do |format|
          if @order.save
            @order.update_column(:order_status, 1)
            # format.html { redirect_to order_confirmation_order_path(@order.order_token), notice: 'Order was successfully created.' }
            # format.json { render :show, status: :created, location: @order }
            flash[:notice] = "successful notice here."
            redirect_to order_confirmation_order_path(@order.order_token)
            else
              # format.html { render :new }
              # format.json { render json: @order.errors, status: :unprocessable_entity }
              flash[:alert] = "failed notice here.  View directions."
              redirect_to @order
            end
          end
        end
      end

无论我使用flash[]还是respond_to,成功订单或失败订单都不会显示Flash消息。我在上面的代码中都留下了,respond_to被注释掉了

我主要希望收到有关失败订单的消息,因为该订单的表单条目之一具有一条带有消息的验证,并且必须进行显示以使客户知道他们输入的问题是很重要的。失败时,我会在 CMD中得到此信息:

No template found for OrdersController#create, rendering head :no_content

现在,与使用相同布局的其他控制器相比,此控制器中的唯一区别是此create方法具有。valid?

我认为这是阻止通知显示的原因。

我如何获得成功创建和失败的Flash消息?

1 个答案:

答案 0 :(得分:0)

对于else条件,您没有if @order.valid?阻止。如果记录无效,则该方法立即结束,并尝试使用与不存在的控制器动作(OrdersController#create)相同的名称来呈现模板。

您可以尝试以下操作:

    if @order.valid? && @order.save
      flash[:notice] = "successful notice here."
      redirect_to order_confirmation_order_path(@order.order_token)
    else
      flash[:alert] = "failed notice here.  View directions."
      redirect_to @order
    end

@order.update_column(:order_status, 1)逻辑应该稍后再移到模型中(以before_save或类似的方式,因此它不会发出额外的数据库调用)。

调用valid?save之后,您可以使用.errors.full_messages从模型层获取验证错误(也许可以在错误通知中显示这些错误)。