有没有一种简单的说法:否则,如果没有任何循环,则显示“无对象”。似乎应该有一种很好的语法方法来做到这一点,而不是计算 @user.find_object("param") 的长度
问问题
3921 次
4 回答
6
您可以执行以下操作:
if @collection.blank?
# @collection was empty
else
@collection.each do |object|
# Your iteration logic
end
end
于 2012-10-13T05:01:55.947 回答
5
导轨视图
# 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
=> []
于 2012-10-13T05:36:25.843 回答
0
if @array.present?
@array.each do |content|
#logic
end
else
#your message here
end
于 2012-10-13T05:05:24.643 回答
0
我执行以下操作:
<% unless @collection.empty? %>
<% @collection.each do |object| %>
# Your iteration logic
<% end %>
<% end %>
于 2014-07-10T16:51:12.040 回答