Ham*_*ner 44 error-handling ruby-on-rails
我有一个控制器,其中包含多个操作:year和:month作为URL中的属性.我已经创建了一个私有方法check_date来检查日期是否有效,并检查日期是否在将来.
def check_date(year, month)
if month < 1 || month > 12 || year < 2000
flash[:notice] = I18n.t 'archive.invalid_date'
redirect_to :action => 'index'
elsif year > Date.today.year || (year == Date.today.year && month > Date.today.month)
flash[:notice] = I18n.t 'archive.no_future'
redirect_to :action => 'month_index',
:year => Date.today.year,
:month => Date.today.month,
:type => params[:type]
end
end
Run Code Online (Sandbox Code Playgroud)
在redirect_to之后是否存在结束控制器执行的轨道方式?
我能想到的方法是在redirect_to之后抛出一个异常,或者从check_date返回一个值并在每个调用它的动作中检查它 - 比如
def month_index
year = params[:year].to_i
month = params[:month].to_i
if !check_date(year, month)
return
...
end
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有一些很好的轨道方式来做到这一点.我一半希望调用redirect_to rails会认出我想要停止,但这似乎不会发生.
Sli*_*son 48
你也可以这样做:
return redirect_to :action => 'index'
Run Code Online (Sandbox Code Playgroud)
和
return redirect_to :action => 'month_index',
:year => Date.today.year,
:month => Date.today.month,
:type => params[:type]
Run Code Online (Sandbox Code Playgroud)
因为它看起来比将回报放在自己的线上更好(恕我直言).
kch*_*kch 35
您可能想要使用过滤器.
如果您在控制器中将其check_date称为a before_filter,则呈现或重定向的事实将阻止控制器调用操作方法.它在那里结束.
vri*_*h88 16
你可以投入
return false
Run Code Online (Sandbox Code Playgroud)
您希望在您的操作中执行代码的任何地方停止
redirect_to只是告诉rails完成时要渲染的内容.如果你在你真正想要的那个之后添加其他render或redirect_to指令,Rails会感到困惑,所以只需在redirect_to之后从控制器返回 - 它就是"正常"的rails方式.
| 归档时间: |
|
| 查看次数: |
32594 次 |
| 最近记录: |