1

So i have this in my view

<% @events.each do |event| %>
      <% if event.eventcomplete %>
  <% else %>
  <tr>
    <td colspan="7">
      <p>
        No Events could be found.
      </p>
    </td>
</tr>
  <% end %>

This is on my search results page,

However what im wanting if there is no eventcomplete, Just display one No events found,

At the moment i'm gettting around 100 events found but, None of them are complete. So i'm getting around 100 "No Events could be found"

Thanks for any help

Sam

sam roberts
  • 217
  • 3
  • 12

4 Answers4

2

I don't know what your code looks like, but something smells wrong to me that you're filtering by eventcomplete in your view both for determining which rows to display and for whether or not to show your "No results" message. Presumably you will later want to do other things using this collection (like pagination), so I'd suggest filtering the collection in the controller:

# controller code
@in_progress_events = @events.where(eventcomplete: false)

Once the collection is being properly filtered before it hits the view, check out the points in this answer for tips on display: Rails: An elegant way to display a message when there are no elements in database

Community
  • 1
  • 1
spike
  • 9,794
  • 9
  • 54
  • 85
1

Your code is missing an <% end %> tag.

<% @events.each do |event| %>
  <% if event.eventcomplete %>
     [insert view code to show if event.eventcomplete is true]
  <% else %> 
    <tr>
      <td colspan="7">
        <p>
          No Events could be found.
        </p>
      </td>
    </tr>
  <% end %>
<% end %>
Andrew Hendrie
  • 6,205
  • 4
  • 40
  • 71
0

Actually the code is doing exactly what it should do,

your html Block was defined in your each block, this is why it got raised 100 times.

I just fixed it with Helper Variables, but it is just a workaround

You should make use of more static methods in your models, just define it

Please make sure your business logic holds place in your models:

Fat models, Thin Controllers/Views

this should work

<% @there_is_no_eventcomplete = false %>
<% @events.each do |event| %>
   <% if event.eventcomplete %>
      @there_is_no_eventcomplete = true
   <% end %> 
<% end %> 
<% if @there_is_no_eventcomplete == false %>
  <tr>
    <td colspan="7">
      <p>
        No Events could be found.
      </p>
    </td>
  </tr>
<% end %>
0

You want to use a scope on your model which you can then call in the controller. I'm not sure how you've set up your model or how you determine if an event is completed, so lets assume you have a boolean attribute completed on your model:

event.rb

class Event
  def self.completed
    where(complete: false)
  end
end

controller

@events = Event.completed

view

<% unless @events.nil?
  <% @events.each do |event|%>
    // your code
  <% end %>
<% else %>
  // your code
<% end %>
margo
  • 2,927
  • 1
  • 14
  • 31