Rails after_initialize only on "new"
Putting the logic in the controller could be the best answer as you stated, but you could get the after_initialize
to work by doing the following:
after_initialize :add_productdef add_product self.product ||= Product.newend
That way, it only sets product if no product exists. It may not be worth the overhead and/or be less clear than having the logic in the controller.
Edit: Per Ryan's answer, performance-wise the following would likely be better:
after_initialize :add_productdef add_product self.product ||= Product.new if self.new_record?end
Surely after_initialize :add_product, if: :new_record?
is the cleanest way here.
Keep the conditional out of the add_product function
If you do self.product ||= Product.new
it will still search for a product every time you do a find
because it needs to check to see if it is nil or not. As a result it will not do any eager loading. In order to do this only when a new record is created you could simply check if it is a new record before setting the product.
after_initialize :add_productdef add_product self.product ||= Product.new if self.new_record?end
I did some basic benchmarking and checking if self.new_record?
doesn't seem to affect performance in any noticeable way.