Reputation: 2363
I'm quite new to Rails. I am trying to find an array of dates between two dates and do this automatically with after_create after creating a specific record.
I have Model Project with columns project.prep_start and project.prep_end....both type Date.
After I create a Project record, I'd like to find the array of dates between project.prep_start and project.prep_end.
Ultimately, I am trying to automatically create many Event records where the Event.occurs_on date column is the same as a date in the project.prep_start..project.prep_end array....but first I have to find the array.
I've written this concerns file...but it keeps throwing an "undefined method `each' for nil:NilClass" error because (I think) I'm not creating the array.
I am trying not to use any gems and just do it the full way.
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
def add_events
@event_dates.each do |event_date|
self.events.create!(occurs_on: event_date)
end
end
end
Upvotes: 0
Views: 1338
Reputation: 2363
Ok...I got it to work without errors. I needed to "require date" and use self.columnname not model.columnname
module AddEvents
extend ActiveSupport::Concern
included do
after_save :event_dates, :add_events
end
def event_dates
require 'date'
(self.prep_start.to_date .. self.prep_end)
end
def add_events
event_dates.each do |event_date|
self.events.create!(occurs_on: event_date)
end
end
end
Upvotes: 0
Reputation: 13615
(Date.current...Date.current+1.month).to_a
is a perfectly good way to get an array of dates.
What you are doing at @event_dates.each
is call .each
on the instance variable `@event_dates'
this needs a value.
If you want to call it on the result of the module method event_dates
instead. you have to give prep_start
and prep_end
values (which I assume they do not have after you only call .new
).
Upvotes: 1
Reputation: 649
Calling the function event_dates
does not automatically set the instance variable @event_dates
. You should be calling the it as a function, i.e. without the @. Alternatively, you can set the instance variable in the event_dates
function.
I also see you're calling the event_dates function from the after_create hook. It's really not necessary in this case.
module AddEvents
extend ActiveSupport::Concern
included do
after_create :add_events
end
def event_dates
@project = Project.new
@[email protected]_end
end
def add_events
event_dates.each do |event_date|
self.events.create!(occurs_on: event_date)
end
end
end
Upvotes: 1