重定向或渲染以检测此Rails闪存?

时间:2014-09-04 06:10:51

标签: javascript ruby-on-rails flash

在我的Rails网站上,当用户通过表单添加产品时,我需要将它们带到产品的页面并显示闪存(闪存将为空白),我将能够在我的JavaScript中检测到;我正在使用我在application.html.erb中设置的自定义闪存。我不确定是否需要使用重定向或渲染。这是我的创建动作(不起作用):

def create
    @product = Product.new(product_params)
    @product.set_user!(current_user)
    respond_to do |format|
      if @product.save
                if !current_user.braintree_customer_id?
                    flash.now[:addmethod] = ""
                    format.html {render :action => "show"}
                else
                    format.html {render :action => "show"}
                end
      else
        flash.now[:alert] = "Woops, looks like something went wrong."
        format.html {render :action => "create"}
      end
    end

end

那么我需要使用什么?渲染还是重定向?

2 个答案:

答案 0 :(得分:0)

成功创建show后,您需要重定向到product操作,如果出现错误,则需要呈现new

您可以将create操作更新为:

def create
  @product = Product.new(product_params)
  @product.set_user!(current_user)
  respond_to do |format|
    if @product.save
      flash.now[:addmethod] = "" unless current_user.braintree_customer_id?
      format.html { redirect_to @product }
    else
      flash.now[:alert] = "Woops, looks like something went wrong."
      format.html { render "new" }
    end
  end
end

您的展示操作必须如下所示:

def show
  @product = Product.find(params[:id])
  ... # other code, if you need

  respond_to do |format|
    format.html
  end
end

答案 1 :(得分:0)

轻微整洁 - 为了更容易阅读我使用了答案部分(尽管它不是答案!)

if @product.save
  if !current_user.braintree_customer_id?
    flash.now[:addmethod] = ""
  end
  format.html {render :action => "show"}
else
  flash.now[:alert] = "Woops, looks like something went wrong."
  format.html {render :action => "create"}