SamuraiBlue
SamuraiBlue

Reputation: 861

Rails: How to check the number of each do

I'd like to know the number of each do in view.

For example,

  <% schedule.rooms.each do |r| %>
    <% r.events.each do |e| %>

If there is no r.events, I'd like to add something.

  <% schedule.rooms.each do |r| %>
    <% r.events.each do |e| %>
      <% if _r.events is not exist_ %>
        do something

It would be appreciated if you could give me any advice.

Upvotes: 0

Views: 124

Answers (1)

Mohamad
Mohamad

Reputation: 35349

Check to see if the current room instance in the loop has any events associated with it, using any?.

<% schedule.rooms.each do |room| %>
  <% if room.events.any? %>
    there are events, loop over them...
    <% room.events.each |event| %>
       do something with `event` instance 
    <% end %>
  <% else %>
    no events, do something else
  <% end %>
<% end %>

You can also invert the logic and use none? or empty?

<% if room.events.none? %>

<% if room.events.empty? %>

Or use unless.

<% unless room.events.any? %>

Upvotes: 1

Related Questions