0

My desired end result is that I want to group events on the events#index page by 3 time periods: Today, Tomorrow and This week. Ideally, it should be sorted by the visitor's time zone, but, the primary use case is EST if that matters.

It's just a fairly simple Rails app that you can check out here: https://github.com/moizk/events

I'm fairly new to Rails, so I assume this sort of thing is handled by the Controller, and creating three instance variables instead of:

@events = Event.all

It should be something like:

@todaysevents = Events.where(some logic in here)
@tomorrowsevents = Events.where(some logic in here)

I just can't figure out what that logic should be.

4

1 回答 1

1

I would recommend adding three scopes to the model, replacing event_start_at with whatever time field you are using:

class Event < ActiveRecord::Base
  scope :today, lambda { where(event_start_at: Time.zone.now.all_day }
  scope :tomorrow, lambda { where(event_start_at: 1.day.from_now.all_day }
  scope :this_week, lambda { where(event_start_at: Time.zone.now.all_week }   
end

And using them in the controller:

@events_today = Event.today
@events_tomorrow = Event.tomorrow
@events_this_week = Event.this_week

If you follow Sandi Metz's "one instance variable per action" rule, which I quite like, you might prefer to wrap these events in an object:

@events = {
  today: Event.today,
  tomorrow: Event.tomorrow,
  this_week: Event.this_week
}

And then use them in the view like @events[:today], @events[:tomorrow], @events[:this_week].

You could even wrap the hash in an OpenStruct to allow @events.today, @events.tomorrow, @events.this_week, but this is probably well into bike shedding territory.

于 2013-03-29T19:31:37.213 回答