How to override “new” method for a rails model

后端 未结 7 719
南笙
南笙 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:38

    This reeks of the factory method patttern...seek it out.

    If you're reluctant for some reason to go with create_date per @Pasta, then possibly create just a simple ruby object (not ActiveRecord backed), named YourModelFactory/Template/Whatever with two instance vars - you can use your standard params[:foo] to assign these - then define and call a method on that class that returns your real objects.

    Your controller logic now looks something like this:

    mmf  = MyModelFactory.new(params[:foo])
    objs = mmf.create_real_deal_models
    

    Good luck.

提交回复
热议问题