Rails 模型、视图、控制器和助手:什么去哪里了? [英] Rails Model, View, Controller, and Helper: what goes where?

查看:22
本文介绍了Rails 模型、视图、控制器和助手:什么去哪里了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby on Rails 开发(或一般的 MVC)中,我应该遵循什么快速规则来放置逻辑.

In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic.

请给予肯定的回答 - 把这个放在这里,而不是不要把那个放在那里.

Please answer in the affirmative - With Do put this here, rather than Don't put that there.

推荐答案

MVC

控制器:将代码放在这里,用于确定用户想要什么,决定给他们什么,确定他们是否登录,他们是否应该看到某些数据等. 最后,控制器查看请求并计算出要显示的数据(模型)和要呈现的视图.如果您对代码是否应该放入控制器有疑问,那么它可能不应该.保持你的控制器 skinny.

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:视图应该只包含显示你的数据(模型)的最少代码,它不应该做大量的处理或计算,它应该显示计算(或汇总)的数据模型,或从控制器生成.如果你的 View 真的需要做 Model 或 Controller 无法完成的处理,把代码放在 Helper 中.视图中的大量 Ruby 代码使页面标记难以阅读.

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.

模型:您的模型应该所有与您的数据相关的代码(构成您网站的实体,例如用户、帖子、帐户、朋友等).) 生活.如果代码需要保存、更新或汇总与您的实体相关的数据,请将其放在这里.它将在您的视图和控制器中重复使用.

Model: Your model should be where all your 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.

这篇关于Rails 模型、视图、控制器和助手:什么去哪里了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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