user4227507
user4227507

Reputation:

Ruby on Rails Display the future date from the database that is closest to today's

In my Ruby on Rails application I am building a cinema system.

On index.html.erb what I want to do is make it so that if the film is not yet released it shows the release date (that works) but if it has already been released and there are showings for that film then display the next date and time it is being shown.

Below is the index.html.erb code that I am trying to use to do this but isn't working.

<% if not film.release_date.blank? %>
    <% if film.release_date > Date.today %>
        Release Date: <%= film.release_date.strftime("%e %B %Y ") %>
    <% else %>
        Next Showing: 
        <% film.showings.each do |showing| %>
            <% if showing.show_date == Date.today %>
                <%= showing.show_date %><br>    
            <% end %>
        <% end %>
    <% end %>
<% end %>

Upvotes: 0

Views: 289

Answers (2)

user4227507
user4227507

Reputation:

After adapting the code by @Geoffroy I have been able to do this correctly using .take(1):

Next Showing: 
<% film.showings.take(1).each do |showing| %>
        <%= film.showings.select{|s| s.show_date >= Date.today}.sort_by(&:show_date).first.show_date.strftime("%A %e %B %Y") %>
<% end %>

Upvotes: 0

Jaffa
Jaffa

Reputation: 12710

You are restricting your view to today's showing, so maybe this is why you don't see anything.

<% if showing.show_date == Date.current %>
    <%= showing.show_date %><br>    
<% end %>

Try to change your code to something like:

<% film.showings.select{|s| s.show_date >= Date.current}.each do |showing| %>
  <%= showing.show_date %><br>    
<% end %>

Or if you really want only the next showing :

<%= film.showings.select{|s| s.show_date >= Date.current}.sort_by(&:show_date).first.show_date %>

I used enumerable methods here but if this is database objects you can also use where and order_by.

Upvotes: 1

Related Questions