有没有简单的说法:否则,如果没有任何循环,请显示“没有对象”。似乎应该有一个很好的语法方法来做到这一点而不是计算@ user.find_object(“param”)的长度
答案 0 :(得分:6)
您可以执行以下操作:
if @collection.blank?
# @collection was empty
else
@collection.each do |object|
# Your iteration logic
end
end
答案 1 :(得分:5)
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)
在nil
为空时将返回@products
。
<强>红宝石强>
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
=> []
答案 2 :(得分:0)
if @array.present?
@array.each do |content|
#logic
end
else
#your message here
end
答案 3 :(得分:0)
我执行以下操作:
<% unless @collection.empty? %>
<% @collection.each do |object| %>
# Your iteration logic
<% end %>
<% end %>