新手:VIEW上的三元"if"条件语法

Lee*_*fin 7 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我想有if条件逻辑,如:

var == 10 ? “10? : “Not 10?
Run Code Online (Sandbox Code Playgroud)

在Rails VIEW上.我尝试的是以下内容:

<%= session[:id]=="out"? link_to "Sign in", login_path : link_to "Sign out", logout_path%>
Run Code Online (Sandbox Code Playgroud)

我知道它看起来很奇怪,并且毫不奇怪它不起作用.所以,如果我想在VIEW上使用三元if条件,在我的情况下,正确的方法是什么?

---------还有一个条件---------

我希望在其他情况下有两个 "link_to"

-----我收到的错误信息--------

compile error

syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
...ession[:id]=="out" ? link_to "Sign in",
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 12

试试这个(唯一diffrence之间有一个空格",并?和使用括号)

<%= session[:id]=="out" ? link_to("Sign in", login_path) : link_to("Sign out", logout_path) %>
Run Code Online (Sandbox Code Playgroud)

在Ruby中,Altough括号是可选的,在某些情况下需要维护运算符优先级.

恕我直言三元运算符很难读.你也可以做一些更冗长的事情:

<%= link_to("Sign in", login_path) if session[:id] == "out" %>
<%= link_to("Sign out", logout_path) if session[:id] != "out" %>
Run Code Online (Sandbox Code Playgroud)