使用redirect_to后如何停止控制器的执行? (使用Rails) [英] How do I stop controller execution after using redirect_to? (Using Rails)

查看:93
本文介绍了使用redirect_to后如何停止控制器的执行? (使用Rails)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,具有多个操作,从URL获取:year和:month作为
属性。我已经将一个私人方法check_date设置为
检查日期是否有效,并检查日期是否在将来。

I have a controller with multiple actions that take :year and :month as attributes from the URL. I have made a private method check_date to check the date is valid and check the date is not in the future.

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


redirect_to之后终止控制器执行?

Is there a rails way of ending controller execution after the redirect_to?

我可以想到的方法是在redirect_to之后抛出异常,或者从check_date返回一个值,并在调用它的每个动作中检查它 - 类似于



Ways I can think of are either to throw an exception after the redirect_to or to return a value from check_date and check it in each action that calls it - something like

def month_index 
  year = params[:year].to_i
  month = params[:month].to_i
  if !check_date(year, month)
    return
  ...
end

但我想知道是否有一些很好的导轨方式来做到这一点。我是一半
希望调用redirect_to rails会识别我想要
停止,但似乎不会发生。

But I wonder if there is some nice rails way of doing this. I was half hoping that having called redirect_to rails would recognise I wanted to stop, but that doesn't seem to happen.

推荐答案

您可能想使用过滤器。

如果您将 check_date 控制器中的 before_filter ,它呈现或重定向的事实将阻止控制器调用action方法。然后结束那里。

If you call your check_date as a before_filter in the controller, the fact that it rendered or redirected will prevent the controller from ever calling the action method. It ends there and then.

这篇关于使用redirect_to后如何停止控制器的执行? (使用Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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