ruby-on-rails - 失败时显示Braintree错误

标签 ruby-on-rails error-handling haml braintree

您好,我正在尝试让我的Braintree帐户在创建交易时显示错误,但似乎无法正常工作

- flash.each do |key, value|
              %div{:class => "alert alert-#{key}"}= value


def update
    result = Braintree::Transaction.sale(
        :amount => params[:amount_to_add].to_f,
        # :order_id => "order id",
        :customer_id => customer.customer_cim_id,
        :tax_amount => (params[:amount_to_add].to_f / 11).round(2),
        :options => {
            :submit_for_settlement => true
        }

    )
    if result.success?
      logger.info "Added to #{params[:amount_to_add].to_f} to #{customer.first_name} #{customer.last_name} (#{customer.customer_cim_id})"
      customer.store_credit.add_credit(params[:amount_to_add].to_f)
      redirect_to myaccount_store_credit_path
      # , :notice => "Successfully updated store credit."
    else
      result.errors.each do |error|
        puts error.message
        customer.errors.add(:base, error.message)
        render :show, :notice => error.message
      end
    end
  end

最佳答案

我相信您可能看不到错误的原因是因为:notice方法上的render选项,这是多余的,因为render似乎并没有使用:notice选项,仅使用了redirect_to。您可能只是将错误添加到flash中,但请注意,在您的 View 中,您必须遍历Flash中的错误以呈现它。

我认为您可以这样做的另一种方式是将付款方式添加到用户模型中

class User|Customer
   ...

   def process_braintree_payment(amount)
     result = Braintree::Transaction.sale(
        :amount => amount.to_f,
        # :order_id => "order id",
        :customer_id => customer_cim_id,
        :tax_amount => (amount.to_f / 11).round(2),
        :options => {
            :submit_for_settlement => true
        }
    )
    add_braintree_errors(result.error) unless result.success?
   end

   def add_braintree_errors(error_object)
     error_object.each do |error|
       errors.add(:braintree, error.message)
     end
   end
end

class XController
  def update
    @customer.process_braintree_payment(params[:amount_to_add])
    if @customer.errors.empty?
      logger.info "Added to #{params[:amount_to_add].to_f} to #{@customer.first_name} #{@customer.last_name} (#{@customer.customer_cim_id})"
      @customer.store_credit.add_credit(params[:amount_to_add].to_f)
      redirect_to myaccount_store_credit_path
      # , :notice => "Successfully updated store credit."
    else
      render :show
    end
  end
end

在您看来,您可以访问@customer变量,或者更好地可以将错误对象存储在ActionController#flash中,但是请注意,对Flash消息使用相同的键将覆盖先前的值。

关于ruby-on-rails - 失败时显示Braintree错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38097339/

相关文章:

vba - VBA错误处理,将错误定义为错误

ruby-on-rails - HAML - 如何创建表单验证并显示错误消息?

Ruby:循环哈希并检查键是否存在以确定要显示的标记和数据

CSS float 复制到右边

ruby-on-rails - 将 options_from_collection_for_select 中的字符串大写

PHP自定义错误页面

java - Thread.setDefaultUncaughtExceptionHandler 中的应用程序崩溃

ruby-on-rails - 将 HAML 与 RSPEC 集成

javascript - 脉动或闪烁的进度条

ruby-on-rails - 如何设计 current_user 工作?