2012-10-13 81 views

Respuesta

6

Usted puede hacer algo como:

if @collection.blank? 
    # @collection was empty 
else 
    @collection.each do |object| 
    # Your iteration logic 
    end 
end 
+3

esta es la manera normal aunque prolija de hacerlo. Tenga en cuenta que 'blank?' Puede sombrear algunos problemas (el valor no debe ser 'nil'),' empty? 'Es más específico. – tokland

0
if @array.present? 
    @array.each do |content| 
    #logic 
    end 
else 
    #your message here 
end 
5

rieles ver

# 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) volverá nil cuando @products está vacía.

Rubí

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 
=> [] 
0

hago lo siguiente:

<% unless @collection.empty? %> 
<% @collection.each do |object| %> 
    # Your iteration logic 
    <% end %> 
<% end %> 
Cuestiones relacionadas