【问题标题】:Rails controllers: halt action execution after renderRails 控制器:渲染后停止动作执行
【发布时间】:2014-05-10 04:25:47
【问题描述】:

我有一个由方法提交调用的 Rails 4.0.2 控制器操作。在此方法中,我检查特定字段以匹配条件,如果不匹配,我想向用户显示错误并再次调用 render new,而无需在方法中进行任何进一步的操作。于是我写了:

  discount_coupon = DiscountCoupon.where(code: discount_code).first

  if discount_coupon.nil? || (discount_coupon.present? && !discount_coupon.currently_active?)
    flash[:alert] = t("flash.entries.create.invalid_coupon_code")
    render :new
    return
  end

  @entry.save

因此,在我的应用程序中,当 discount_coupon 变量错误并且程序进入条件时,它应该在 return 上停止执行,但不知何故它没有,并且调用了 @entry.save 方法并搞砸了整个东西。

我做错了什么?感谢您的帮助!

【问题讨论】:

  • 该代码在我看来是正确的。尝试将您的条件更改为“如果为真”以确保您正在执行返回。
  • 使用render :new and return

标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord


【解决方案1】:

你为什么不把@entry.save 用一个else 条件括起来并去掉return?因此,如果折扣券条件失败,它会呈现操作 :new 否则它只会保存条目。

【讨论】:

    【解决方案2】:

    按照建议,试试if/else 有条件的:

    discount_coupon = DiscountCoupon.where(code: discount_code).first
    
    if discount_coupon.nil? || (discount_coupon.present? && !discount_coupon.currently_active?)
      flash[:alert] = t("flash.entries.create.invalid_coupon_code")
      render :new
    else
        @entry.save
    end
    

    您可以在确定此代码正常工作后对其进行重构。

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      相关资源
      最近更新 更多