0

I'm working on a Rails HAML View and I'm trying to display together two fields: the first one is String datatype and the other one is Boolean datatype, I'm trying with this line of code:

      %td=students.name + " " + students.status ? '(Passed)' : ''

As you can see I'm using a ternary operator to cast true to Passed and false to blank.

However, I'm getting this error:

error_message

Also, if I avoid ternary operator I got the same output error.

My question is: how can I cast these two fields and at the same time show "passed" if it is true?

Thanks a lot

2
  • 1
    To be clear, you are not trying to concatenate a string with a boolean (that's not valid in ruby). Your problem here is all about the order of operation, namely, trying to do multiple things in one line without brackets. Commented Aug 26, 2022 at 15:40
  • As a best practice, consider moving your strings into your locale file, rather than hard-coding English strings in your views. Commented Aug 26, 2022 at 15:52

2 Answers 2

1

May be interpolation instead of concatenation?

And don't need ternary operator in that case because nil.to_s == ""

%td="#{students.name} #{'(Passed)' if students.status}"

or even just

%td #{students[:name]} #{'(Passed)' if students[:status]}
Sign up to request clarification or add additional context in comments.

1 Comment

If you're going to wrap the entire line in ", then drop the " and the =, they are redundant: %td #{students[:name]} #{'(Passed)' if students[:status]}
0

try this:

%td=students.name + " " + (students.status ? '(Passed)' : '' )

1 Comment

thank you so much @LesNightingill it works as expected, all the best

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.