简体   繁体   English

为什么控制器操作应该调用一个模型方法而不是初始查找或新的?

[英]Why controller action should call one model method other than an initial find or new?

I have almost all of the "shared" statements in functions in my model. 我的模型中的函数几乎都有“共享”语句。 The problem is that I am getting the following error, when I need to use more then one of these functions in my controller: 问题是我得到以下错误,当我需要在我的控制器中使用多个这些函数时:

Controller action should call one model method other than an initial find or new 控制器操作应该调用除初始查找或新查询之外的一种模型方法

and the IDE goes deeper explaining that: 并且IDE更深入地解释:

This inspection warns if a controller action contains more than one model method call, after the initial .find or .new. 如果控制器操作在初始.find或.new之后包含多个模型方法调用,则此检查会发出警告。 It's recommended that you implement all business logic inside the model class, and use a single method to access it. 建议您在模型类中实现所有业务逻辑,并使用单个方法来访问它。

Is this mean that all of the logic should be put in more complex model functions? 这是否意味着所有逻辑都应该放在更复杂的模型函数中? I have thought that the work of the controller is to call model functions and passes the results to the view. 我认为控制器的工作是调用模型函数并将结果传递给视图。

If I put back the model functions code back to the controller, everything will work, but I will get a code duplication in all my controller actions. 如果我将模型函数代码放回控制器,一切都会工作,但我会在所有控制器操作中得到代码重复。

So, what is the right approach here? 那么,这里的正确方法是什么?

The warning message indeed means that the logic should be put in a single model function, but not necessarily more complex ones. 警告消息确实意味着逻辑应该放在单个模型函数中,但不一定是更复杂的函数。 To avoid model duplication and/or the "fat model" problem, you may need to introduce additional classes that the model relies on. 为避免模型重复和/或“胖模型”问题,您可能需要引入模型所依赖的其他类。

Yes, the work of the control is to call model functions, but only as a thin veneer, per this inspection guideline of one model function per controller action aside from an initial create/find. 是的,控件的工作是调用模型函数,但仅作为薄单板,根据初始创建/查找之外的每个控制器操作的一个模型函数的检查指南。

I'm not sure I understand your comment about getting code duplication in your controller if you move functions back up, since you can always introduce shared functions at the controller level. 如果你重新移动函数,我不确定你理解你在控制器中获取代码重复的评论,因为你总是可以在控制器级别引入共享函数。 But again, that's not the recommended approach of "thin controller" and "reasonably thin model" with supporting classes as required. 但同样,这不是“瘦控制器”和“合理瘦身模型”的推荐方法,而是根据需要提供支持类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM