为什么三重运算符不能与重定向工作 [英] Why won't ternary operator work with redirect

查看:155
本文介绍了为什么三重运算符不能与重定向工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢三元运算符。它真的清理代码看起来,但我有一个情况下,它不会在Rails控制器中正确的行为。



我得到一个语法错误:意外的tSYMBEG,期望关键字_或者{'或'('



我一直得到这个问题,



我不知道有关这个规则吗?

p>

  if nexti == 0 then 
redirect_to:back
else
redirect_to edit_playt_path(id:actform ['playt_id'],i:nexti)
end

nexti == 0?redirect_to:back:redirect_to edit_playt_path(id:actform ['playt_id'],i:nexti)


解决方案

由于散列的隐含性质

$



Ruby / Rails会暗示你的重定向参数是一个在你的例子中有些尴尬的哈希。重定向它在以下场景中将其视为哈希,它将其解析为

  nexti == 0? redirect_to({:back,:redirect_to edit_playt_path(id:actform ['playt_id'],i:nexti})

这是无效的,如果你明确定义你的哈希/参数,它应该工作

  nexti == 0?redirect_to返回):redirect_to(edit_playt_path({id:actform ['playt_id'],i:nexti}))

大多数ruby / rails devs会告诉你避免三元的原因,以及一般的人类对于正在发生的事情的理解。Ruby被认为是一种表达性的语言,所以拥抱它。



return redirect_to(:back)if nexti == 0
redirect_to(edit_playt_path({id:actform ['playt_id'],i:nexti}) )


I love the ternary operator. It really cleans up the code look, but I have a case where it won't behave correctly in a Rails controller.

I get a syntax error: unexpected tSYMBEG, expecting keyword_do or '{' or '('

I consistently get this issue, it light switches on changing the statement below to a ternary operator. It always happens when I'm trying to use it in conjunction with a redirect statement.

Am I unaware of a rule about this?

if nexti==0 then
  redirect_to :back
else
  redirect_to edit_playt_path(id: actform['playt_id'], i: nexti)
end

nexti==0 ? redirect_to :back : redirect_to edit_playt_path(id: actform['playt_id'], i: nexti)

解决方案

Because of the implied nature of the hash

Ruby / Rails will imply your argument to redirect is a hash which has some awkward implications in your example

When ruby implies the arguments to redirect it sees it as a hash in the following scenario it is parsing it as

nexti==0 ? redirect_to({:back, : redirect_to edit_playt_path(id: actform['playt_id'], i: nexti})

which is invalid, it should work if you explicitly define your hash / argument

nexti==0 ? redirect_to(:back) : redirect_to(edit_playt_path({id: actform['playt_id'], i: nexti}))

most ruby / rails devs will tell you to avoid ternaries for reasons like this, and also general human comprehension of what is going on. Ruby was ment to be an expressive language, so embrace it.

return redirect_to(:back) if nexti==0
redirect_to(edit_playt_path({id: actform['playt_id'], i: nexti}))

这篇关于为什么三重运算符不能与重定向工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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