Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override "new" method for a rails model

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?

like image 358
Lan Avatar asked Dec 07 '10 13:12

Lan


2 Answers

Strictly, although late, the proper way to override new in a model is

def initialize(args)
    #
    # do whatever, args are passed to super
    #
    super
end
like image 50
s1mpl3 Avatar answered Nov 15 '22 21:11

s1mpl3


Don't override initialize It could possibly break a lot of stuff in your models. IF we knew why you needed to we could help better ( don't fully understand your explanation of the form being a skeleton, you want form attributes to create other attributes?? see below). I often use a hook as Marcel suggested. But if you want it to happen all the time, not just before you create or save an object, use the after_initialize hook.

def after_initialize
  # Gets called right after Model.new
  # Do some stuff here
end

Also if you're just looking for some default values you can provide default accessors, something like: (where some_attribute corresponds with the column name of your model attribute)

def some_attribute
  attributes[:some_attribute] || "Some Default Value"
end

or a writer

def some_attribute=(something)
  attributes[:some_attribute] = something.with_some_changes
end

If I understand your comment correctly, it looks like you expose a form that would make your model incomplete, with the other attributes based on parts of this form? In this case you can use any of the above methods after_initialize or some_attribute= to then create other attributes on your model.

like image 27
brad Avatar answered Nov 15 '22 19:11

brad