渲染无法在ActiveRecord :: Rollback方法中的抢救中渲染正确的模板 [英] Render failing to render correct template in rescue_from ActiveRecord::Rollback method

查看:84
本文介绍了渲染无法在ActiveRecord :: Rollback方法中的抢救中渲染正确的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个电子商务网站的结帐页面,我的交易相当长,它创建了一个新的用户模型和一个新的订单模型。我将这些模型的创建包装在一个事务中,以便如果对一个模型的验证失败,则另一个模型不会在数据库中徘徊。这是我的OrdersController中的精简代码:

I'm building the checkout page for an e-commerce site, and I have a fairly long transaction that creates a new User model and a new Order model. I wrapped the creation of these models in a transaction so that if validation for one fails, the other isn't hanging around in the database. Here's the trimmed-down code in my OrdersController:

rescue_from ActiveRecord::Rollback, with: :render_new

def render_new
  render action: 'new'
end

ActiveRecord::Base.transaction do
  @user = User.new params[:user]
  unless @user.save
    raise ActiveRecord::Rollback
  end
  //More stuff
  ...
  @order = Order.new params[:order]
  ...
  unless @order.save
    raise ActiveRecord::Rollback
  end
end

我看到的错误是:


缺少模板顺序/ create,application / create with {:locale => [:en],:formats => [:html],:handlers => [:erb,:builder,:coffee]}

Missing template orders/create, application/create with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}

我很困惑为什么它尝试呈现订单/创建和应用/创建模板而不是呈现订单/新建。

I'm confused as to why its trying to render the templates orders/create and application/create instead of rendering orders/new.

有没有更好的方法可以强制交易失败以使t他会回滚吗?

Is there a better way to force the transaction to fail so that the rollback will occur?

推荐答案

我认为将事务包装在begin / rescue块中时,意图会更清晰一些。 / p>

I think the intention is a bit clearer when wrapping the transaction in a begin/rescue block.

def create
  begin 
    ActiveRecord::Base.transaction do
      @user = User.new params[:user]
      unless @user.save
        raise ActiveRecord::Rollback
      end
      //More stuff
      ...
      @order = Order.new params[:order]
      ...
      unless @order.save
        raise ActiveRecord::Rollback
      end
    end
  rescue ActiveRecord::Rollback
    render action: "new" and return
  end
end

您需要在 create 方法中返回,否则它将继续执行到该方法的结尾,并且将发生Rails默认渲染(在这种情况下,这意味着尝试查找 create .___ 模板)

You need to return in the create method, otherwise it's execution will continue to the end of the method and Rails default render will occur (in this case it means attempting to find a create.___ template).

如果你不喜欢开始/救援块,您只需添加并返回 raise

If you don't like the begin/rescue block you can just add an and return to the raise lines

raise ActiveRecord::Rollback and return

这篇关于渲染无法在ActiveRecord :: Rollback方法中的抢救中渲染正确的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆