如何检查 rails 4 上的变量是否为空?
How to check if variable empty on rails 4?
如何在我的控制器中创建 if else 语句。问题是@topvideo 显示了当天的最新视频,但如果当天没有人上传任何内容,它就会抛出错误。并且此功能位于主页面上,因此您无法看到页面的其余部分。
我想说如果有@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>
您可以使用 blank? 方法来检查 nil
和 empty
:
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
如何在我的控制器中创建 if else 语句。问题是@topvideo 显示了当天的最新视频,但如果当天没有人上传任何内容,它就会抛出错误。并且此功能位于主页面上,因此您无法看到页面的其余部分。
我想说如果有@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>
您可以使用 blank? 方法来检查 nil
和 empty
:
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