views:

135

answers:

1

Is it ok to instantiate an object in a View before passing it to a partial?

<%= render :partial => "trade_new", :locals => {:trade=>Trade.new("e", "b") } %>

Or is better to instantiate any objects in the Controller as instance variables:

@trade = Trade.new("e", "b")

and then pass the instance variable to a partial in the view like this:

<%= render :partial => "trade_new", :locals => {:trade => @trade } %>

My guess is it's better to instantiate new objects in the controller to avoid duplication - such as in a case where multiple templates may need to pass this new object to a partial from the same action.

+2  A: 

Firstly, it is okay to instantiate an object in the view. Nothing will probably blow up in your face. However, then you miss the whole advantage of splitting your architecture into tiers.

It is better to instantiate the object in the controller. Some of the reasons include - better reuse, much simpler testing, better design because of the decoupling.

See the articles on presentation patterns here.

Anirudh
Yes, nothing bad will happen just because you instantiate in the view, but it isn't a good design usually :)
workmad3
My one personal exception to this rule is if I need to instantiate an empty object to pass to a form, or to grab a bunch of objects to display a select box with. I do both of those in the View (or a Helper for the latter) without shedding a single MVC tear.
Ian Terrell