I have a Service model with title:string description:string date:datetime. I would like to implement a system to create multiple services based on date patterns, e.g. when the user create a new service for Oct 20 he can choose to “repeat” it once a month for 5 months. The final result should be that 6 services are created, due to Oct 20, Nov 20, etc.
The way I implemented this is working, but really ugly. I have something like this in my view:
<input type="radio" name="each" value="none" checked="true"/>No<br/>
<input type="radio" name="each" value="week"/>Each week for <input type="text" name="weeks_number" /> weeks.<br/>
<input type="radio" name="each" value="month"/>Each month for <input type="text" name="months_number" /> months.<br/>
In my controller, I calculate the dates the various services will take place, than create N Service objects (where N is the number specified in params[:weeks_number] or params[:months_number]) and save each of them.
This doesn’t sound good, does it? First of all, I was thinking about moving all the logic for creating “multiple” services into the model. The next big thing is: how to clean up the view and the controller? I’d like my controller to be as simple as
@service = Service.new(params[:service])
In order to do this I’ll have to change something in the model (this should be called virtual attributes) in order to let the controller believe that something like
@service.repeat_method = "month"
@service.repeat = 6
actually makes sense and will cause the creation of 6 different rows in my db, when calling @service.save.
Here is where I’m stuck and in need of help. Does my reasoning make any sense? And how to implement this?
Thank you.
I wouldn’t have the
repeat_methodandrepeatattributes on a Service instance doing the magic you describe in the question. I’d have acreate_repeatsmethod something like this:Then your controller code will be something like the following:
I know this doesn’t defer all the logic to the model but some parameters really need specific logic to determine how they are translated from the view to the model layer.
You may also want to check that
params[:weeks_number]orparams[:months_number]are a valid number and that the user has not specified both.