How to override “new” method for a rails model

后端 未结 7 715
南笙
南笙 2020-12-16 03:01

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 instan

7条回答
  •  [愿得一人]
    2020-12-16 03:48

    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
    

提交回复
热议问题