需要一些关于试图在ApplicationController

时间:2016-09-04 03:22:36

标签: ruby-on-rails

首先,这个领先的代码已经可以工作了,我试图验证项目数量库存的东西,并弹出一个警报,不会将项目添加到购物车,我一直在尝试尝试,但还没有能够处理那,提前谢谢。

所以在CartController中我有这个:

class CartController < ApplicationController
before_filter :authenticate_user!
#validate :@product.ensure_product_quantity, on: :update

def update

begin

  @product = Product.find product_params[:id]
  #@product.ensure_product_quantity
  logger.debug "#{@product.ensure_product_quantity}"

  #if @product.ensure_product_quantity < 0
    #flash.now[:notice] = "Item added to cart"
    #session[:cart] << @product.item_for_cart(product_params[:quantity]).with_indifferent_access
    #session[:cart].delete_at(cart_item_params)
    #flash.now[:notice] = "True"
  #else
    #flash.now[:alert] = "No enough product left"
    #flash.now[:notice] = "False"
  #end

  #flash[:alert] = "Not enough product left" if @product.ensure_product_quantity > 0

  session[:cart] << @product.item_for_cart(product_params[:quantity]).with_indifferent_access
  flash.now[:notice] = "Item added to cart"
  #flash.now[:alert] = "No enough product left" if @product.item_for_cart(product_params[:quantity]) > @product.current_quantity

rescue => e

  if e.is_a? ActionController::ParameterMissing
    flash.now[:alert] = "Please make a selection to add this item"
  else
    flash.now[:alert] = "Sorry, there was a problem adding this item"
  end

end
end

在产品型号上有ensure_product_quantity

  def ensure_product_quantity
      items.each do |item|
      errors.add(:base, "Not enough of '#{item.product.title}' left") if item.quantity > item.product.current_quantity
  end
      #logger.debug "llega"
  end

以上代码适用于从菜单中选择所需项目,然后单击添加到购物车按钮,我想要检查该产品是否有足够的产品,如果没有,请不要将该项目添加到购物车和向用户显示一条消息。

0 个答案:

没有答案