Ok to instantiate an object in the View?

2019-03-04 08:31发布

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.

1条回答
姐就是有狂的资本
2楼-- · 2019-03-04 08:52

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.

查看更多
登录 后发表回答