In Ruby on Rails every cycle, is there a good way to do something if nothing has been repeated?

Is there an easy way to say: else, if nothing has been looped, show "No objects." It seems like there should be a good syntax way to do this, and not calculate the length of @ user.find_object ("param")

+6
source share
4 answers

You can do something like:

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

View 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) will return nil when @products 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 => [] 
+5
source
 if @array.present? @array.each do |content| #logic end else #your message here end 
0
source

I do the following:

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

Source: https://habr.com/ru/post/927621/


All Articles