NothingToSeeHere
NothingToSeeHere

Reputation: 2363

How to create multiple records from a range of dates in Rails 4

I have two models, Project and Event. Project has_many events.

I want to automatically create many Events after_create of one Project.

My Project model has two Date columns prep_start and prep_end

I am trying to find an array of dates between prep_start and prep_end

I have created a concern that is supposed to automatically create events after_create a new @Project. My concern (Add_Events.erb) file looks like this:

 module AddEvents
 extend ActiveSupport::Concern

   included do
    after_create :event_dates, :add_events
    end

    def event_dates 
      @project = Project.new

     (@[email protected]_end)
    end
    end

   def add_events

   @event_dates.each do |event_date|
   self.events.create!(occurs_on: event_date)
   end
   end

I can't get the array to complete.

Upvotes: 0

Views: 713

Answers (2)

Mark Meeus
Mark Meeus

Reputation: 707

Ruby ranges (x .. y) are enumerable objects, this means you can do .each on them.

Iterating a range of dates works fine, but iterating a range of datetimes will yield every second between the start and the end of range. (It will also issue a lot of warnings, because the succ method on datetime is obsolete)

So you'll have to make sure your items are of type Date.

It is safe to call to_date on instances of Date, Time, DateTime and TimeWithZone, the example below should do the trick

(project.start_at.to_date .. project.end_at.to_date).each do |date|
    Event.create(:occurs_at => date)
end

Upvotes: 1

Marcelo Ribeiro
Marcelo Ribeiro

Reputation: 1738

I assume you want to create events daily, right? First, you need to find the the array of dates between your start date and end date. There is a very nice ruby gem that helps you do that here: IceCube.

Once you have your array of dates, you can loop through them and create your events:

def create_events
   # Assuming you have @event_dates = ["2014-09-20", "2014-09-21", "2014-09-22", "2014-09-23"]
   @event_dates.each do |event_date|
     self.events.create!(event_date: event_date)
   end
end

Upvotes: 1

Related Questions