在Ruby on Rails的每个循环中,如果没有迭代,有没有一种好的方法可以做某些事情?

时间:2012-10-13 04:46:35

标签: ruby-on-rails ruby

有没有简单的说法:否则,如果没有任何循环,请显示“没有对象”。似乎应该有一个很好的语法方法来做到这一点而不是计算@ user.find_object(“param”)的长度

4 个答案:

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