确定要在视图中实例化对象吗? [英] Ok to instantiate an object in the View?

查看:62
本文介绍了确定要在视图中实例化对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将对象传递给局部对象之前,可以在View中实例化对象吗?

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

或者最好将Controller中的任何对象实例化为实例变量:

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

然后将实例变量传递给视图中的局部变量,如下所示:

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

我的猜测是,最好在控制器中实例化新对象以避免重复-例如在多个模板可能需要通过同一动作将新对象传递给部分对象的情况下.

解决方案

首先,可以实例化视图中的对象.可能什么也不会炸开你的脸.但是,您然后会错过将体系结构分成多个层的全部优势.

最好在控制器中实例化对象.原因包括-更好的重用,更简单的测试,由于去耦而导致的更好的设计.

请参见此处.

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.

解决方案

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.

这篇关于确定要在视图中实例化对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆