samedi 22 août 2015

How to check if variable empty on rails 4?

How can i make an if else statement in my controller. The problem is that @topvideo shows the latest video of the day but what if no one has uploaded it anything for the day it throws an error. and this feature is on the main page so you cant see the rest of the page because of it.

I want to say if theres @topvideo.title empty run this:

@topvideo = Video.order("cached_votes_up DESC, created_at DESC").where("created_at >= ?", Time.now.in_time_zone("Eastern Time (US & Canada)").beginning_of_month)

else run this:

@topvideo = Video.order("cached_votes_up DESC, created_at DESC").where("created_at >= ?", Time.zone.now.beginning_of_day)

Controller

def index
  @videos = Video.all.order("cached_votes_up DESC, created_at DESC")
  @items = Video.all.order("cached_votes_up DESC, created_at DESC")
  @items_by_day = @items.group_by { |t| t.created_at.beginning_of_day }
  @topvideo = Video.order("cached_votes_up DESC, created_at DESC").where("created_at >= ?", Time.zone.now.beginning_of_day)    
end

(view)

<div class="novideo">


        <h1>#1</h1>
        <h2>TuChoice<br>
        Today</h2>

        <div class="artisthead"></div>

        <h3><%= @topvideo.first.title %></h3>
        <h4><%= @topvideo.first.artist %></h4>

        <p></p>
    </div>

    <iframe id="video" src="//www.youtube.com/embed/<%= @topvideo.first.url %>" frameborder="0" allowfullscreen></iframe>

</div>

Aucun commentaire:

Enregistrer un commentaire