【问题标题】:Redirect or render to detect this Rails flash?重定向或渲染以检测此 Rails 闪存?
【发布时间】:2014-09-04 06:10:51
【问题描述】:

在我的 Rails 网站上,当用户通过表单添加产品时,我需要将他们带到产品页面并显示一个可以在我的 JavaScript 中检测到的 flash(flash 将为空白);我正在使用我在 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

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

【问题讨论】:

  • 你应该 redirectshow 行动。
  • @RAJ...new 我相信?
  • @nithin 让我重新措辞一下,他应该在创建操作中创建记录后重定向控件以显示操作。
  • @RAJ... 对。我正在担任else 的一部分。

标签: javascript ruby-on-rails flash


【解决方案1】:

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

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"}

【讨论】:

    【解决方案2】:

    成功创建product后需要重定向到show动作,如果出现错误,需要渲染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
    

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

    def show
      @product = Product.find(params[:id])
      ... # other code, if you need
    
      respond_to do |format|
        format.html
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      相关资源
      最近更新 更多