Rails redirect_to != return

kingwkb · 2014年09月15日 · 最后由 kingwkb 回复于 2014年09月15日 · 2684 次阅读

我在 Rails 4.1 中 使用 redirect_to 不用再使用 return 了

之前的版本中使用 redirect_to 之后还要再使用 return

现在这个小贴士可以去掉了

贴代码看看?

redirct_to "xxx" and return?

在 4.1 中 before_action 中 redirect_to xxxx and return 会报错

完全不知道你在说什么,还是贴代码来看看吧

楼主说的应该是:

redirect_to info_path, notice: '信息修改成功' and return

我在建新项目的时候,没有 return,发现也没有出问题,当时也在好奇这个事情。

#4 楼 @raven 好吧,我没表达清楚
#5 楼 @JeskTop 是正确的

小贴士的那种情况是在 action 中:

def show
  if condition?
    redirect_to path
  end

  do_something
  render
end

这样会产生二次 render 出错,需要在 redirect_to 后面加上 return。

但是我一般都是这样写:

def show
  if condition?
    redirect_to path
  else
    do_something
    render
  end
end

这样确保每个分支只有一次 render,是没有问题的。

和这个写法类似,写到 filter 里面也没问题,rails 判断在 filter 里面进行过 render,就不会执行后面的 filter 和 action 了。

#7 楼 @Rei 如果是 action 中只写了 redirect_to 没有 render 也不会报错

def show
  if condition?
    redirect_to path
  end

  do_something
end

#8 楼 @kingwkb 不会。这种 condition return 的写法可能来自 C 语言风格,但是 redirect_to 并不会 return 会给这样写的人造成误解,所以有那条 tips。

#8 楼 @kingwkb 你不知道别人会不会在后面加多个 render,redirect_to 或者 do_something 会抛异常..redirect_to != return 只是提醒,不是一定非要那么做

#8 楼 @kingwkb

你看

def test
  if true
    redirect_to home_path
  end

  p "You should not see me !"
end

Output

Redirected to http://localhost:3000/my
"You should not see me !"
Completed 302 Found in 6ms (ActiveRecord: 0.7ms)

这就是为啥说 redirect_to != return

cckkll 请教一个关于 redirect_to 的问题 提及了此话题。 08月04日 19:02
需要 登录 后方可回复, 如果你还没有账号请 注册新账号