How to override "new" method for a rails model

ruby-on-rails

Solution

As @brad says, you definitely do not want to override initialize. Though you could override after_initialize, that doesn't really look like what you want here. Instead, you probably want to add a factory method to the class like @Pasta suggests. So add this to your model:

def self.build_for_range(start_date, end_date, attributes={})
  start_date.upto(end_date).map { new(attributes) }
end

And then add this to your controller:

models = MyModel.build_for_range(start_date, end_date, params[:my_model])
if models.all?(:valid?)
  models.each(&:save)
  # redirect the user somewhere ...
end

Problem

In my rails app I have a model with a start_date and end_date. If the user selects Jan 1, 2010 as the start_date and Jan 5, 2010 as the end_date, I want there to be 5 instances of my model created (one for each day selected). So it'll look something like ``` Jan 1, 2010 Jan 2, 2010 Jan 3, 2010 Jan 4, 2010 Jan 5, 2010 ``` I know one way to handle this is to do a loop in the controller. Something like... ``` # ...inside controller start_date.upto(end_date) { my_model.new(params[:my_model]) } ``` However, I want to keep my controller skinny, plus I want to keep the model logic outside of it. I'm guessing I need to override the "new" method in the model. What's the best way to do this?

Original source