I would like to have the if condition logic like:
var == 10 ? “10″ : “Not 10″
on Rails VIEW. What I tried is following:
<%= session[:id]=="out"? link_to "Sign in", login_path : link_to "Sign out", logout_path%>
I know it looks odd, and unsurprisingly it does not work. So, if I would like to use ternary if condition on VIEW, what is the correct way to do in my case?
---------One more condition---------
I would like to have two "link_to" in else condition
-----The error message I got--------
compile error
syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
...ession[:id]=="out" ? link_to "Sign in",
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Since the Conditional Operator '?:' takes three operands to work, hence they are also called ternary operators. Working: Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then Expression2 will be executed and the result will be returned.
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .
The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way.
Try this (the only diffrence is a space between "
and ?
and the use of parentheses)
<%= session[:id]=="out" ? link_to("Sign in", login_path) : link_to("Sign out", logout_path) %>
Altough parentheses are optional in Ruby they are needed to maintain operator precedence in some cases.
IMHO ternary operators are hard to read. You could also do something more verbose:
<%= link_to("Sign in", login_path) if session[:id] == "out" %>
<%= link_to("Sign out", logout_path) if session[:id] != "out" %>
session[:id]=="out"?
looks wrong. It should be
session[:id]=="out" ?
By the way if you need more link in the else part switch to an if else. It could be more clean:
<% if condition %>
link
<% else %>
link
link
<% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With