ItsJoeTurner
ItsJoeTurner

Reputation: 603

If two DateTime stamps are the same in Rails

I have created a simple appointment system, and I now need to display something inside a loop if there's two or more appointments with the same date and time. The appointments are displayed in order of time, so they're just appearing one after the other.

Controller

def index
  @todays_apps = current_user.appointments.order(time ASC)
end 

View

<% @todays_apps.each do |app| %>
  <%= app.business_name %>
  <%= app.business_address %>
  <%= app.time %>
<% end %>

I'm looking to display a message or icon the appointment shares a date and time with another appointment. Tried a collection of things with no luck.

Upvotes: 0

Views: 59

Answers (2)

Rails Guy
Rails Guy

Reputation: 3866

Try Like this:

controller:

def index
  @appointments = current_user.appointments.order("time ASC")
  @todays_apps = @appointments.group_by(&:time)
end

View:

<% @todays_apps.each do |time, appointments| %>
  <%= time %>
  <% appointments.each do |appointment| %>
    <%= appointment.business_name %>
    <%= appointment.business_address %>
  <% end %>
<% end %>

It will list all the appointments for particular time. Thanks

Upvotes: 0

Manoj Sehrawat
Manoj Sehrawat

Reputation: 1303

You can group your collection by time and modify your iteration accordingly. You can group it like

@todays_apps.group_by(&:time) 

The outcome will be something like

=> { timestamp1 => [app1,app2], timestamp2 => [app3], timestamp3 => [app4]}

Or you can try a quick hacky way like:

  <% previous_time = nil %>
  <% @todays_apps.each do |app| %>
    <%= app.business_name %>
    <%= app.business_address %>
    <%= 'Your message or class or anything' if previous_time == app.time %>
    <%= previous_time = app.time %>
  <% end %>

Upvotes: 1

Related Questions