【问题标题】:How do I access "assigns" after "render :template => ..."?如何在“render :template => ...”之后访问“assigns”?
【发布时间】:2010-09-17 14:35:48
【问题描述】:

我的 ApplicationController 中有一个错误处理方法:

rescue_from ActiveRecord::RecordNotFound, :with => :not_found

def not_found(exception)
  @exception = exception
  render :template => '/errors/not_found', :status => 404
end

RAILS_ROOT/app/views/errors/not_found.html.erb,我有这个:

<h1>Error 404: Not Found</h1>
<%= debug @exception %>

@exception 始终是nil。我试过debug assigns,但总是{}。调用render :template 时不会复制分配吗?如果是这样,我怎样才能得到它们?

我在边缘 Rails 上。

【问题讨论】:

    标签: ruby-on-rails ruby actionview


    【解决方案1】:

    这很奇怪,我不知道为什么。作为替代方案,您是否尝试过将异常作为显式本地传递?

    def not_found(exception)
      render :template => '/errors/not_found', 
             :status   => 404, 
             :locals   => {:exception => exception}
    end
    

    和观点:

    <h1>Error 404: Not Found</h1>
    <%= debug exception %> <!-- Note no '@' -->
    

    【讨论】:

    • 哦,等等!是的!没有@!
    【解决方案2】:

    ActionController::Base 的 API 文档看来,您应该尝试一下:

    render :template => '/errors/not_found', :status => 404, :locals => {:exception => exception}
    

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 2019-02-21
      • 2021-02-18
      • 2019-04-26
      相关资源
      最近更新 更多