pete_schuster
pete_schuster

Reputation: 227

Simple Rails Conditional Statement

Pretty simple I'm sure... but I can't figure out why it wouldn't work.

<tr<% if film.viewed == true %> class="viewed"<% end %>>

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

<tr<% if film.viewed == true puts class=\"viewed\" end %>>

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

Upvotes: 0

Views: 1629

Answers (5)

ChuckJHardy
ChuckJHardy

Reputation: 7066

I would rather do something like this.

<tr class="<%= film.viewed ? "viewed" : "" -%>"></tr>

Upvotes: 0

zetetic
zetetic

Reputation: 47548

I think this is easer to read:

<%= content_tag(:tr, "", :class => film.viewed? ? "viewed" : nil) %>

Upvotes: 2

DigitalRoss
DigitalRoss

Reputation: 146053

<tr <%= film.viewed ? 'class="viewed"' : 'class="notviewed" %> >

So, some notes.

  • To do a full if ... end you would have needed a ";" or newline before the end.
  • Do you actually have a local variable or parameter called film?
  • You need <%= and not just <% in order to interpolate the final result of your template code.
  • I imagine the erb template driver calls the to_s method on whatever result it gets, and since nil.to_s returns "" then you are safe with a stand-alone false if statement, which has the effect as an expression of returning nil. But somehow having the expression always return a value one would be willing to see interpolated would seem to make sense.

Upvotes: 0

jmcnevin
jmcnevin

Reputation: 1285

Your best bet would be something like the following...

<tr <%= 'class="viewed"' if film.viewed? -%>>

All boolean ActiveRecord columns get a question mark method that will return a true or false. As MySQL stores booleans as 1/0, I usually use the question mark method just to be safe.

Upvotes: 5

EnabrenTane
EnabrenTane

Reputation: 7466

I'm guessing film.viewed isn't true, but another value.

try something to the effect of

<tr <%= "class='viewed'" if film.viewed %> >

Upvotes: 0

Related Questions