如何检查轨道4上的变量是否为空?

时间:2015-08-23 01:24:49

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 controller

如何在我的控制器中创建if else语句。问题是@topvideo显示当天的最新视频,但如果没有人在它抛出错误的那天上传了任何内容,该怎么办?并且此功能位于主页面上,因此您无法看到页面的其余部分。

我想说,如果theres @topvideo.title为空,请执行此操作:

@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)

否则运行:

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

控制器

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

(适用视图)

<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>

1 个答案:

答案 0 :(得分:0)

您可以使用blank?方法检查nilempty

if @topvideo.blank?
  @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
  @topvideo = Video.order("cached_votes_up DESC, created_at DESC").where("created_at >= ?", Time.zone.now.beginning_of_day)
end