Ruby-on-rails Rails 模型、视图、控制器和助手:什么去哪里了?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/60658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Model, View, Controller, and Helper: what goes where?
提问by theschmitzer
In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic.
在 Ruby on Rails 开发(或一般的 MVC)中,我应该遵循什么快速规则来放置逻辑。
Please answer in the affirmative - With Do put this here, rather than Don't put that there.
请肯定地回答 -把这个放在这里,而不是不要把那个放那里。
回答by pauliephonic
MVC
MVC
Controller: Put code here that has to do with working out what a user wants, and deciding what to give them, working out whether they are logged in, whether they should see certain data, etc. In the end, the controller looks at requests and works out what data (Models) to show and what Views to render. If you are in doubt about whether code should go in the controller, then it probably shouldn't. Keep your controllers skinny.
控制器:将代码放在这里,用于确定用户想要什么,决定给他们什么,确定他们是否登录,他们是否应该看到某些数据等。 最后,控制器查看请求并计算出要显示的数据(模型)和要呈现的视图。如果您对代码是否应该放入控制器有疑问,那么它可能不应该。保持你的控制器瘦。
View: The view should only contain the minimum code to display your data (Model), it shouldn't do lots of processing or calculating, it should be displaying data calculated (or summarized) by the Model, or generated from the Controller. If your View really needs to do processing that can't be done by the Model or Controller, put the code in a Helper. Lots of Ruby code in a View makes the pages markup hard to read.
视图:视图应该只包含显示数据(模型)的最少代码,它不应该做大量的处理或计算,它应该显示由模型计算(或汇总)的数据,或从控制器生成的数据。如果你的 View 真的需要做 Model 或 Controller 无法完成的处理,把代码放在 Helper 中。视图中的大量 Ruby 代码使页面标记难以阅读。
Model: Your model should be where allyour code that relates to your data (the entities that make up your site e.g. Users, Post, Accounts, Friends etc.) lives. If code needs to save, update or summarise data related to your entities, put it here. It will be re-usable across your Views and Controllers.
模型:您的模型应该是与您的数据(构成您的站点的实体,例如用户、帖子、帐户、朋友等)相关的所有代码所在的位置。如果代码需要保存、更新或汇总与您的实体相关的数据,请将其放在这里。它将在您的视图和控制器中重复使用。
回答by jcoby
To add to pauliephonic's answer:
添加到pauliephonic的答案:
Helper: functions to make creating the view easier. For example, if you're always iterating over a list of widgets to display their price, put it into a helper (along with a partial for the actual display). Or if you have a piece of RJS that you don't want cluttering up the view, put it into a helper.
Helper:使创建视图更容易的功能。例如,如果您总是遍历一个小部件列表以显示它们的价格,请将其放入一个帮助器(以及用于实际显示的部分)。或者,如果您有一块 RJS,但不想弄乱视图,请将其放入 helper 中。
回答by S?ren Spelling Lund
The MVC pattern is really only concerned with UI and nothing else. You shouldn't put any complex business logic in the controller as it controls the view but not the logic. The Controller should concern itself with selecting the proper view and delegate more complex stuff to the domain model (Model) or the business layer.
MVC 模式实际上只关心 UI,不关心其他任何事情。您不应该在控制器中放置任何复杂的业务逻辑,因为它控制视图而不是逻辑。控制器应该关注自己选择正确的视图并将更复杂的东西委托给域模型(模型)或业务层。
Domain Driven Design has a concept of Services which is a place you stick logic which needs to orchestrate a number of various types of objects which generally means logic which doesn't naturally belong on a Model class.
领域驱动设计有一个服务的概念,它是一个你坚持逻辑的地方,它需要编排许多不同类型的对象,这通常意味着不自然属于模型类的逻辑。
I generally think of the Service layer as the API of my applications. My Services layers usually map pretty closely to the requirements of the application I'm creating thus the Service layer acts as a simplification of the more complex interactions found in the lower levels of my app, i.e. you could accomplish the same goal bypassing the Service layers but you'd have to pull a lot more levers to make it work.
我通常将服务层视为我的应用程序的 API。我的服务层通常与我正在创建的应用程序的要求非常接近,因此服务层充当了在我的应用程序较低级别中发现的更复杂交互的简化,即您可以绕过服务层实现相同的目标但你必须拉动更多的杠杆才能让它发挥作用。
Note that I'm not talking about Rails here I'm talking about a general architectural style which addresses your particular problem.
请注意,我在这里不是在谈论 Rails,而是在谈论解决您的特定问题的通用架构风格。
回答by maddin2code
Perfect explanations here already, one very simple sentence as conclusion and easy to remember:
完美的解释已经在这里,一个非常简单的句子作为结论并且易于记忆:
We need SMART Models, THIN Controllers, and DUMB Views.
我们需要智能模型、薄控制器和哑视图。
回答by John Topley
The Rails way is to have skinny controllers and fat models.
Rails 的方式是拥有瘦控制器和胖模型。
回答by srboisvert
Do put stuff related to authorization/access control in the controller.
将与授权/访问控制相关的东西放在控制器中。
Models are all about your data. Validation, Relationships, CRUD, Business Logic
模型都是关于你的数据。验证、关系、CRUD、业务逻辑
Views are about showing your data. Display and getting input only.
视图是关于显示您的数据。仅显示和获取输入。
Controllers are about controlling what data goes from your model to your view (and which view) and from your view to your model. Controllers can also exist without models.
控制器是关于控制哪些数据从您的模型到您的视图(以及哪个视图)以及从您的视图到您的模型。控制器也可以在没有模型的情况下存在。
I like to think of the controller as a security guard/receptionist who directs you the customer(request) to the appropriate counter where you ask a teller (view) a question. The teller (view) then goes and gets the answer from a manager (model), who you never see. You the request then go back to the security guard/receptionist (controller) and wait until you are directed to go another teller (view) who tells you the answer the manager (model) told them in response to the other teller's (view) question.
我喜欢将控制器视为一名保安/接待员,他将您的客户(请求)引导到您向柜员(查看)问题的适当柜台。出纳员(视图)然后去从经理(模型)那里得到答案,你从未见过他。然后您将请求返回给保安/接待员(控制员)并等到您被指示去另一个柜员(查看),他告诉你经理(模特)在回答其他柜员(查看)问题时告诉他们的答案.
Likewise if you want to tell the teller (view) something then largely the same thing happens except the second teller will tell you whether the manager accepted your information. It is also possible that the security guard/receptionist (controller) may have told you to take a hike since you were not authorized to tell the manager that information.
同样,如果您想告诉出纳员(查看)某事,那么会发生大致相同的事情,只是第二个出纳员会告诉您经理是否接受了您的信息。也有可能是保安/接待员(管制员)告诉您去远足,因为您无权告诉经理该信息。
So to extend the metaphor, in my stereotyped and unrealistic world, tellers (views) are pretty but empty-headed and often believe anything you tell them, security guard/receptionists are minimally polite but are not very knowledgeable but they know where people should and shouldn't go and managers are really ugly and mean but know everything and can tell what is true and what isn't.
因此,为了扩展这个比喻,在我的刻板印象和不切实际的世界中,出纳员(观点)很漂亮但头脑空洞,并且经常相信你告诉他们的任何事情,保安人员/接待员很有礼貌但不是很博学,但他们知道人们应该在哪里和不应该去,经理们真的很丑很刻薄,但什么都知道,可以分辨什么是真的,什么不是。
回答by James A. Rosen
One thing that helps separate properly is avoiding the "pass local variables from controller to view" anti-pattern. Instead of this:
有助于正确分离的一件事是避免“将局部变量从控制器传递到视图”反模式。取而代之的是:
# app/controllers/foos_controller.rb:
class FoosController < ApplicationController
def show
@foo = Foo.find(...)
end
end
#app/views/foos/show.html.erb:
...
<%= @foo.bar %>
...
Try moving it to a getter that is available as a helper method:
尝试将其移至可用作辅助方法的 getter:
# app/controllers/foos_controller.rb:
class FoosController < ApplicationController
helper_method :foo
def show
end
protected
def foo
@foo ||= Foo.find(...)
end
end
#app/views/foos/show.html.erb:
...
<%= foo.bar %>
...
This makes it easier to modify what gets put in "@foo" and how it is used. It increases separation between controller and view without making them any more complicated.
这使得修改“@foo”中的内容及其使用方式变得更加容易。它增加了控制器和视图之间的分离,而不会使它们变得更加复杂。
回答by Paul Wicks
Well, it sort of depends upon what the logic has to deal with...
嗯,这有点取决于逻辑必须处理的内容......
Often, it makes sense to push more things into your models, leaving controllers small. This ensures that this logic can easily be used from anywhere you need to access the data that your model represents. Views should contain almost no logic. So really, in general, you should strive to make it so that you Don't Repeat Yourself.
通常,将更多的东西放入模型中是有意义的,而让控制器变小。这确保可以从任何需要访问模型表示的数据的任何地方轻松使用此逻辑。视图应该几乎不包含逻辑。所以真的,总的来说,你应该努力做到这一点,这样你就不会重复自己。
Also, a quick bit of google reveals a few more concrete examples of what goes where.
此外,谷歌的一小部分揭示了一些更具体的例子,说明了什么。
Model: validation requirements, data relationships, create methods, update methods, destroy methods, find methods (note that you should have not only the generic versions of these methods, but if there is something you are doing a lot, like finding people with red hair by last name, then you should extract that logic so that all you have to do is call the find_redH_by_name("smith") or something like that)
模型:验证需求、数据关系、创建方法、更新方法、销毁方法、查找方法(注意,你不仅应该拥有这些方法的通用版本,而且如果有一些你经常做的事情,比如找到红色的人按姓氏的头发,那么您应该提取该逻辑,以便您所要做的就是调用 find_redH_by_name("smith") 或类似的东西)
View: This should be all about formatting of data, not the processing of data.
视图:这应该是关于数据的格式化,而不是数据的处理。
Controller: This is where data processing goes. From the internet: "The controller's purpose is to respond to the action requested by the user, take any parameters the user has set, process the data, interact with the model, and then pass the requested data, in final form, off to the view."
控制器:这是数据处理的地方。来自互联网:“控制器的目的是响应用户请求的操作,获取用户设置的任何参数,处理数据,与模型交互,然后将请求的数据以最终形式传递给看法。”
Hope that helps.
希望有帮助。
回答by Anutosh
In simple terms, generally, Modelswill have all the codes related to table(s), their simple or complex relationships (think them as sql queries involving multiple tables), manipulation of the data/variables to arrive at a result using the business logic.
简单来说,通常, 模型将拥有与表相关的所有代码,它们的简单或复杂关系(将它们视为涉及多个表的 sql 查询),使用业务逻辑对数据/变量进行操作以得出结果.
Controllerswill have code/pointers towards the relevant models for the job requested.
控制器将具有指向所请求作业的相关模型的代码/指针。
Viewswill accept the user input/interaction and display the resultant response.
视图将接受用户输入/交互并显示结果响应。
Any major deviation from these will put unwanted strain on that part and the overall application performance may get impacted.
与这些的任何重大偏差都会给该部分带来不必要的压力,并且整体应用程序性能可能会受到影响。
回答by Anutosh
Testing, Testing ... Put as much logic as possible in the model and then you will be able to test it properly. Unit tests test the data and the way it is formed by testing the model, and functional tests test the way it is routed or controlled by testing the controllers, so it follows that you can't test the integrity of the data unless it is in the model.
测试,测试……在模型中加入尽可能多的逻辑,然后你就可以正确地测试它。单元测试通过测试模型来测试数据及其形成方式,功能测试通过测试控制器来测试数据的路由或控制方式,因此您无法测试数据的完整性,除非它在该模型。
j
j

