2016-08-01 56 views
2

我有从其他宝石如何从错误中挽救在Rails模板(ERB文件)

sample.html.erb

<h1>All The Stuff</h1> 
<% all_the_stuff.each do |stuff| %> 
    <div><%= stuff %></div> 
<% end %> 

lib/random_file.rb

def all_the_stuff 
    if ALL_THE_STUFF.exists? 
     ALL_THE_STUFF 
    else 
     fail AllTheStuffException 
    end 
end 
一些辅助方法ERB模板

现在,如果ALL_THE_STUFF不存在,我会得到ActionView::Template::Error。但是,这不会被控制器级别的异常处理所捕获。 在控制器的情况下,我使用rescue_from拯救了ApplicationController中的例外。有没有一个地方可以把它放在我所有的ERB模板中?

如何处理在模板中捕获的异常(不是由于控制器代码)?

+1

“开始......救援......结束”在ERB中工作得很好。 –

+0

我应该更清楚。在我的应用程序控制器的情况下,我可以做一个'rescue_from'块来救援,但是没有这样的地方可以完成所有的模板。 – absessive

+0

你应该可以用同样的方法做到这一点:rescue_from ActionView :: Template :: Error,用::your_method_here – fanta

回答

-1

我认为一个更好的解决办法是以下几点:

class ThingsController < ApplicationController 
    def sample 
    @things = Thing.all 
    end 
end 


# views/things/sample.html.erb 
<h1>All The Things</h1> 
<% if @things.present? %> 
    <% @things.each do |thing| %> 
    <div><%= thing %></div> 
    <% end %> 
<% else %> 
    There are no things at the moment. 
<% end %> 

这是轨道的方式和使用任何Exception类作为控制流,这通常是一个坏主意避免。