Ruby on Rails 基本概念总结
作为 Rails 的新手,我很难找到提供 Ruby on Rails 概要的网站或参考资料。我对 MVC、ActiveRecord 以及诸如此类的东西有基本的了解,但我很难理解其中的一些关系和基础知识。例如:
- 我需要注意哪些命名约定?
- 控制器操作应该如何构建和命名?
- 在视图中呈现信息的最佳方法是什么(通过
:content_for
或render
部分)以及我不应该使用哪些方法? - 什么应该进入助手,什么不应该进入助手?
- 有哪些常见的陷阱或者我需要从一开始就正确做的事情是什么?
- 如何模块化代码?这就是
lib
文件夹的用途吗?
我在 StackOverflow 上读过很多关于这个问题的回复,但所有这些都只是指向我需要阅读的一本 300 多页的书,而我只想对重要内容进行简洁的总结。
我已经知道一些资源,但没有为新用户提供基本概念的简明摘要:
- http://railscasts.com/ (很好,但支离破碎)
- http://guides.rubyonrails.org/(假设您已经理解一切之间的关系)
- http://ruby.railstutorial.org/ (按颜色绘制,没有很好的总结)
- Rails AntiPatterns(很好,但是在理解任何内容之前你必须阅读整个内容)
- The Rails 3 Way(很好,但同样,你必须阅读全文在你理解任何事情之前)
感谢您提供的任何帮助、参考或指导!
PS 我希望这个 wiki 成为一个动态文档,所以请根据需要添加、编辑等。
Being new to Rails, I am having a difficult time finding a website or reference that gives a run down summary of Ruby on Rails. I understand MVC, ActiveRecord, and that sort of stuff on a basic level, but I am having a hard time understanding some of the relationships and fundamentals. For instance:
- What are all naming conventions I need to be aware of?
- How should controller actions be structured and named?
- What are the best ways to render information in a view (via
:content_for
orrender
a partial) and what are ways I shouldn't use? - What should go into a helper and what shouldn't?
- What are common pitfalls or something I need to do correctly from the very beginning?
- How can you modularize code? Is that what the
lib
folder is for?
I have read a number of responses on StackOverflow in regards to this question, but all of them just point to a 300+ page book I need to read, whereas I just want a concise summary of what's important.
Some resources I am already aware of, but do not offer a concise summary of fundamental concepts for new users:
- http://railscasts.com/ (good, but fragmented)
- http://guides.rubyonrails.org/ (assumes you already understand relationships between everything)
- http://ruby.railstutorial.org/ (paint by colors, no good summary)
- Rails AntiPatterns (great, but you have to read the whole thing before you understand anything)
- The Rails 3 Way (great, but again, you have to read the whole thing before you understand anything)
Thank you for any help, references, or guidance you can provide!
P.S. I would like this wiki to become a living document, so please add to it, edit it, etc. as you feel necessary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1.我需要注意哪些命名约定?
db table 是复数,model 是单数,controller 是复数。因此,您拥有由
users
表支持的User
模型,并且通过UsersController
可见。文件应命名为类名的 Wide_cased 版本。因此
FooBar
类需要位于名为foo_bar.rb
的文件中。如果您使用模块命名空间,则命名空间需要由文件夹表示。因此,如果我们正在讨论Foo::Bar
类,它应该位于foo/bar.rb
中。2.控制器操作应该如何构建和命名?
控制器操作应该是 RESTful 的。这意味着您应该将控制器视为公开资源,而不仅仅是启用 RPC。 Rails 有一个资源成员操作与集合操作的概念。成员操作是在特定实例上操作的操作,例如
/users/1/edit
是用户的编辑成员操作。收集操作是对所有资源进行操作的操作。因此/users/search?name=foo
将是一个集合操作。上面的教程描述了如何在路由文件中实际实现这些想法。
3.在视图中呈现信息的最佳方法是什么(通过
:content_for
或呈现部分内容)以及我不应该使用哪些方法?content_for
应该当您希望能够将 html 从内部模板附加到外部模板时使用 - 例如,能够将视图模板中的某些内容附加到布局模板中。一个很好的例子是添加页面特定的 javascript。部分用于分解大文件,或用于多次呈现相同的信息位。例如,
4.什么应该进入帮助程序,什么不应该进入帮助程序?
您的模板中应该只包含基本分支逻辑。如果你需要做更激烈的事情,应该找帮手。视图中的局部变量是对世界上所有美好和正确事物的憎恶,因此这是一个很好的迹象,表明您应该成为一个帮助者。
另一个原因是纯粹的代码重用。如果您一遍又一遍地做同样的事情,只有轻微的变化,请将其拉入一个助手(如果它是完全相同的事情,它应该是部分的)。
5.常见的陷阱是什么,或者我需要从一开始就正确执行哪些操作?
部分永远不应该直接引用实例 (@) 变量,因为它会阻止重复使用。始终通过
:locals => 传递数据{ :var_name =>; value }
渲染函数的参数。将与渲染视图不直接相关的逻辑排除在视图之外。如果您可以选择在视图中执行某些操作,然后在其他地方执行此操作,则十分之九的情况是在其他位置执行该操作是更好的选择。
我们在 Rails 中有一句口头禅:“胖模型,瘦控制器”。原因之一是模型是面向对象的,控制器本质上是过程性的。还有一个就是模型可以跨控制器,但是控制器不能跨模型。第三个是模型更易于测试。这只是一个好主意。
6.如何模块化代码?这就是 lib 文件夹的用途吗?
lib 文件夹用于存放与模型相关的代码(即不是模型,但将被多个模型使用的代码)。当您需要将某些东西放在那里时,您就会知道,因为您将无法弄清楚将其放入哪个模型中。在那之前,您可以忽略 lib。
需要记住的是,从 Rails 3 开始,lib 不在自动加载路径上,这意味着您需要
require
放入其中的任何内容(或将其添加回)一种自动 require 的方法
lib
目录中的所有模块:1. What are all naming conventions I need to be aware of?
db table is plural, model is singular, controller is plural. so you have the
User
model that is backed by theusers
table, and visible through theUsersController
.files should be named as the wide_cased version of the class name. so the
FooBar
class needs to be in a file calledfoo_bar.rb
. If you are namespacing with modules, the namespaces need to be represented by folders. so if we are talking aboutFoo::Bar
class, it should be infoo/bar.rb
.2. How should controller actions be structured and named?
controller actions should be RESTful. That means that you should think of your controllers as exposing a resource, not as just enabling RPCs. Rails has a concept of member actions vs collection actions for resources. A member action is something that operates on a specific instance, for example
/users/1/edit
would be an edit member action for users. A collection action is something that operates on all the resources. So/users/search?name=foo
would be a collection action.The tutorials above describe how to actually implement these ideas in your routes file.
3. What are the best ways to render information in a view (via
:content_for
or render a partial) and what are ways I shouldn't use?content_for
should be used when you want to be able to append html from an inner template to an outer template -- for example, being able to append something from your view template into your layout template. A good example would be to add a page specific javascript.partials are either for breaking up large files, or for rendering the same bit of information multiple times. For example
4.What should go into a helper and what shouldn't?
your templates should only have basic branching logic in them. If you need to do anything more intense, it should be in a helper. local variables in views are an abomination against all that is good and right in the world, so that is a great sign that you should make a helper.
Another reason is just pure code reuse. If you are doing the same thing with only slight variation over and over again, pull it into a helper (if it is the exact same thing, it should be in a partial).
5. What are common pitfalls or something I need to do correctly from the very beginning?
partials should never refer directly to instance (@) variables, since it will prevent re-use down the line. always pass data in via the
:locals => { :var_name => value }
param to the render function.Keep logic out of your views that is not directly related to rendering your views. If you have the option to do something in the view, and do it somewhere else, 9 times out of 10 doing it somewhere else is the better option.
We have a mantra in rails that is "fat models, skinny controllers". One reason is that models are object oriented, controllers are inherantly procedural. Another is that models can cross controllers, but controllers cant cross models. A third is that models are more testable. Its just a good idea.
6. How can you modularize code? Is that what the lib folder is for?
the lib folder is for code that crosses the concerns of models (i.e. something that isn't a model, but will be used by multiple models). When you need to put something in there, you will know, because you wont be able to figure out what model to put it in. Until that happens, you can just ignore lib.
Something to keep in mind is that as of rails 3, lib is not on the autoload path, meaning that you need to
require
anything you put in there (or add it back in)A way to automatically require all modules in the
lib
directory:我前段时间写了一些命名约定:
Rails conventions
General
All filenames are in Snake_case遵循相同的约定
- 模型:单数(例如
餐厅
)- 控制器:复数(例如
RestaurantsController
)- 数据库中的表:复数(例如
餐馆
)- URL:全部为复数(例如
/restaurants
、/restaurants/:id
、/restaurants/new
)railsgenerate
命令rails g model
Restaurant
name:string rating:integer
rails g migration AddDescriptionTo
Restaurants
description:text
餐厅
index show
模型(单数)
ActiveRecord
方法全部采用单数,因为所有
ActiveRecord
的方法都链接到模型。示例:
-
Restaurant.all
-
Restaurant.create(名称:“汉堡王”,评级:2)
-
Restaurant.find(params[:id])
关联
belongs_to
中的单数。因为它属于一个元素。has_many
中的复数。因为它有很多元素。例如,
路由
资源
当定义资源的路由时,
复数:路由助手
索引
:复数(因为我们正在显示元素列表)。例如restaurants_path
。也可用于创建
。show
:单数(我们只显示一个元素,它需要括号内的元素)。例如restaurant_path(@restaurant)
。也可用于更新
&删除
。新
:单数。例如new_restaurant_path
I wrote some naming conventions some time ago:
Rails conventions
General
All filenames are in snake_case following the same conventions
- Model: singular (e.g.
Restaurant
)- Controller: plural (e.g.
RestaurantsController
)- Table in DB: plural (e.g.
restaurants
)- URL's: all in plural (e.g.
/restaurants
,/restaurants/:id
,/restaurants/new
)rails generate
Commandsrails g model
Restaurant
name:string rating:integer
rails g migration AddDescriptionTo
Restaurants
description:text
rails g controller
Restaurants
index show
Model (singular)
ActiveRecord
methodsAll in singular, because all
ActiveRecord
's methods are linked to the model.Examples:
-
Restaurant.all
-
Restaurant.create(name: "Burger King", rating: 2)
-
Restaurant.find(params[:id])
Associations
belongs_to
. Because it belongs to one element.has_many
. Because it has many elements.e.g.
Routes
Resources
Plural when defining a route for a resource:
Route helpers
index
: plural (because we are showing a list of elements). e.g.restaurants_path
. Can also be used used forcreate
.show
: singular (we are showing just one element, it needs the element inside parenthesis). e.g.restaurant_path(@restaurant)
. Can also be used forupdate
&delete
.new
: singular. e.g.new_restaurant_path
聊天 GPT 答案:
了解 Ruby on Rails 及其约定一开始确实会让人感到不知所措,但一旦熟悉了它的原理,它就会变得更容易导航。让我们分解您的问题,以提供更清晰的观点。
1. 命名约定
User
、ProductCategory
)。数据库表应该是复数的(例如,users
、product_categories
)。Controller
结尾(例如,UsersController
、ProductCategoriesController
)。users/show.html.erb
表示showUsersController
中的 code> 操作)。202401011230_add_email_to_users.rb
)。2. 控制器操作结构和命名
Rails 遵循 RESTful 约定,建议在适用的情况下使用七个标准操作:
index
、show
、new
、<代码>创建、编辑
、更新
和销毁
。围绕资源构建控制器,并尽可能保持操作 RESTful,将每个操作集中在特定的 CRUD 操作上。3. 在视图中渲染信息
render
:非常适合可重用组件(例如表单、页面的各个部分)。使用前导下划线命名部分 (_form.html.erb
),并使用render 'form'
或renderpart: 'form'
渲染它们。:content_for
: 最适合从视图内将内容插入布局的特定区域,例如添加自定义标题或脚本。避免过度使用content_for
来获取自然适合部分结构的内容。4. 帮助程序
帮助程序用于与视图相关的方法,以保持视图代码的整洁和可读性。示例包括格式化日期、数字或字符串,以及生成表单组件或链接。避免将业务逻辑放入助手中;应驻留在模型或服务对象中。
5. 常见陷阱
Chat GPT answers:
Understanding Ruby on Rails and its conventions can indeed feel overwhelming at first, but once you get familiar with its principles, it becomes much easier to navigate. Let’s break down your questions to provide a clearer view.
1. Naming Conventions
User
,ProductCategory
). Database tables should be pluralized (e.g.,users
,product_categories
).Controller
(e.g.,UsersController
,ProductCategoriesController
).users/show.html.erb
for theshow
action inUsersController
).202401011230_add_email_to_users.rb
).2. Controller Actions Structure and Naming
Rails follows RESTful conventions, suggesting the use of seven standard actions where applicable:
index
,show
,new
,create
,edit
,update
, anddestroy
. Structure your controllers around resources and keep actions RESTful when possible, focusing each action on a specific CRUD operation.3. Rendering Information in Views
render
for Partials: Ideal for reusable components (e.g., forms, sections of a page). Name partials with a leading underscore (_form.html.erb
) and render them withrender 'form'
orrender partial: 'form'
.:content_for
: Best for inserting content into specific areas of a layout from within a view, like adding a custom title or scripts. Avoid overusingcontent_for
for content that fits naturally into a partial structure.4. Helpers
Helpers are intended for view-related methods to keep the view code clean and readable. Examples include formatting dates, numbers, or strings, and generating form components or links. Avoid putting business logic in helpers; that should reside in models or service objects.
5. Common Pitfalls