简体   繁体   中英

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")

You can do something like:

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

Rails view

# 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.

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM