[英]In a Ruby on Rails each loop, is there a good way to do something if nothing was iterated?
Is there an easy way to say: else, if there was nothing looped, show 'No objects.' 有没有简单的说法:否则,如果没有任何循环,请显示“没有对象”。 Seems like there should be a nice syntactical way to do this rather than calculate the length of @user.find_object("param") 似乎应该有一个很好的语法方法来做这个而不是计算@ user.find_object(“param”)的长度
You can do something like: 你可以这样做:
if @collection.blank?
# @collection was empty
else
@collection.each do |object|
# Your iteration logic
end
end
Rails view Rails视图
# index.html.erb
<h1>Products</h1>
<%= render(@products) || content_tag(:p, 'There are no products available.') %>
# Equivalent to `render :partial => "product", @collection => @products
render(@products)
will return nil
when @products
is empty. 当@products
为空时, render(@products)
将返回nil
。
Ruby 红宝石
puts "no objects" if @collection.blank?
@collection.each do |item|
# do something
end
# You *could* wrap this up in a method if you *really* wanted to:
def each_else(list, message)
puts message if list.empty?
list.each { |i| yield i }
end
a = [1, 2, 3]
each_else(a, "no objects") do |item|
puts item
end
1
2
3
=> [1, 2, 3]
each_else([], "no objects") do |item|
puts item
end
no objects
=> []
if @array.present?
@array.each do |content|
#logic
end
else
#your message here
end
I do the following: 我做以下事情:
<% unless @collection.empty? %>
<% @collection.each do |object| %>
# Your iteration logic
<% end %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.