Ruby on Rails 基本概念总结

发布于 2024-10-20 05:05:58 字数 1218 浏览 4 评论 0原文

作为 Rails 的新手,我很难找到提供 Ruby on Rails 概要的网站或参考资料。我对 MVC、ActiveRecord 以及诸如此类的东西有基本的了解,但我很难理解其中的一些关系和基础知识。例如:

  1. 我需要注意哪些命名约定?
  2. 控制器操作应该如何构建和命名?
  3. 在视图中呈现信息的最佳方法是什么(通过 :content_forrender 部分)以及我不应该使用哪些方法?
  4. 什么应该进入助手,什么不应该进入助手?
  5. 有哪些常见的陷阱或者我需要从一开始就正确做的事情是什么?
  6. 如何模块化代码?这就是 lib 文件夹的用途吗?

我在 StackOverflow 上读过很多关于这个问题的回复,但所有这些都只是指向我需要阅读的一本 300 多页的书,而我只想对重要内容进行简洁的总结。

我已经知道一些资源,但没有为新用户提供基本概念的简明摘要:

感谢您提供的任何帮助、参考或指导!

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:

  1. What are all naming conventions I need to be aware of?
  2. How should controller actions be structured and named?
  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?
  4. What should go into a helper and what shouldn't?
  5. What are common pitfalls or something I need to do correctly from the very beginning?
  6. 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:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

若水微香 2024-10-27 05:05:58

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。

# app/views/layout/application.rb
<html>
  <head>
    <%= yield :head %>
...

# app/views/foobars/index.html.erb

<% content_for :head do %>
  <script type='text/javascript'>
    alert('zomg content_for!');
  </script>
<% end %>

部分用于分解大文件,或用于多次呈现相同的信息位。例如,

<table>
  <%= render :partial => 'foo_row', :collection => @foobars %>
</table>

# _foo_row.html.erb

<tr>
 <td>
  <%= foobar.name %>
 </td>
</tr>

4.什么应该进入帮助程序,什么不应该进入帮助程序?

您的模板中应该只包含基本分支逻辑。如果你需要做更激烈的事情,应该找帮手。视图中的局部变量是对世界上所有美好和正确事物的憎恶,因此这是一个很好的迹象,表明您应该成为一个帮助者。

另一个原因是纯粹的代码重用。如果您一遍又一遍地做同样的事情,只有轻微的变化,请将其拉​​入一个助手(如果它是完全相同的事情,它应该是部分的)。

5.常见的陷阱是什么,或者我需要从一开始就正确执行哪些操作?

部分永远不应该直接引用实例 (@) 变量,因为它会阻止重复使用。始终通过 :locals => 传递数据{ :var_name =>; value } 渲染函数的参数。

将与渲染视图不直接相关的逻辑排除在视图之外。如果您可以选择在视图中执行某些操作,然后在其他地方执行此操作,则十分之九的情况是在其他位置执行该操作是更好的选择。

我们在 Rails 中有一句口头禅:“胖模型,瘦控制器”。原因之一是模型是面向对象的,控制器本质上是过程性的。还有一个就是模型可以跨控制器,但是控制器不能跨模型。第三个是模型更易于测试。这只是一个好主意。

6.如何模块化代码?这就是 lib 文件夹的用途吗?

lib 文件夹用于存放与模型相关的代码(即不是模型,但将被多个模型使用的代码)。当您需要将某些东西放在那里时,您就会知道,因为您将无法弄清楚将其放入哪个模型中。在那之前,您可以忽略 lib。

需要记住的是,从 Rails 3 开始,lib 不在自动加载路径上,这意味着您需要 require 放入其中的任何内容(或将其添加回)

一种自动 require 的方法lib 目录中的所有模块:

#config/initializers/requires.rb
Dir[File.join(Rails.root, 'lib', '*.rb')].each do |f|
  require f
end

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 the users table, and visible through the UsersController.

files should be named as the wide_cased version of the class name. so the FooBar class needs to be in a file called foo_bar.rb. If you are namespacing with modules, the namespaces need to be represented by folders. so if we are talking about Foo::Bar class, it should be in foo/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.

# app/views/layout/application.rb
<html>
  <head>
    <%= yield :head %>
...

# app/views/foobars/index.html.erb

<% content_for :head do %>
  <script type='text/javascript'>
    alert('zomg content_for!');
  </script>
<% end %>

partials are either for breaking up large files, or for rendering the same bit of information multiple times. For example

<table>
  <%= render :partial => 'foo_row', :collection => @foobars %>
</table>

# _foo_row.html.erb

<tr>
 <td>
  <%= foobar.name %>
 </td>
</tr>

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:

#config/initializers/requires.rb
Dir[File.join(Rails.root, 'lib', '*.rb')].each do |f|
  require f
end
很糊涂小朋友 2024-10-27 05:05:58

我前段时间写了一些命名约定:

Rails conventions

General

All filenames are in Snake_case遵循相同的约定
- 模型:单数(例如餐厅
- 控制器:复数(例如RestaurantsController
- 数据库中的表:复数(例如餐馆
- URL:全部为复数(例如/restaurants/restaurants/:id/restaurants/new

railsgenerate 命令

  • 创建模型:singular(因为模型的名称是单数)。例如 rails g model Restaurant name:string rating:integer
  • 创建迁移:复数 (因为我们使用表的名称)。例如 rails g migration AddDescriptionToRestaurants description:text
  • 创建控制器:复数 例如 < code>rails gcontroller 餐厅 index show

模型(单数)

ActiveRecord 方法

全部采用单数,因为所有 ActiveRecord 的方法都链接到模型。
示例:
- Restaurant.all
- Restaurant.create(名称:“汉堡王”,评级:2)
- Restaurant.find(params[:id])

关联

  • belongs_to 中的单数。因为它属于一个元素。
  • has_many 中的复数。因为它有很多元素。

例如,

class Restaurant < ActiveRecord::Base
  has_many :reviews
end

class Review < ActiveRecord::Base
  belongs_to :restaurant
end

路由

资源

当定义资源的路由时,

resources :restaurants

复数:路由助手

  • 索引复数(因为我们正在显示元素列表)。例如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 Commands

  • Create model: singular (because the name of the model is singular). e.g. rails g model Restaurant name:string rating:integer
  • Create migration: plural (because we use the name of the table). e.g. rails g migration AddDescriptionToRestaurants description:text
  • Create controller: plural e.g. rails g controller Restaurants index show

Model (singular)

ActiveRecord methods

All 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

  • Singular in the belongs_to. Because it belongs to one element.
  • Plural in the has_many. Because it has many elements.

e.g.

class Restaurant < ActiveRecord::Base
  has_many :reviews
end

class Review < ActiveRecord::Base
  belongs_to :restaurant
end

Routes

Resources

Plural when defining a route for a resource:

resources :restaurants

Route helpers

  • index: plural (because we are showing a list of elements). e.g. restaurants_path. Can also be used used for create.
  • show: singular (we are showing just one element, it needs the element inside parenthesis). e.g. restaurant_path(@restaurant). Can also be used for update & delete.
  • new: singular. e.g. new_restaurant_path
画尸师 2024-10-27 05:05:58

聊天 GPT 答案:

了解 Ruby on Rails 及其约定一开始确实会让人感到不知所措,但一旦熟悉了它的原理,它就会变得更容易导航。让我们分解您的问题,以提供更清晰的观点。

1. 命名约定

  • 模型:单数和驼峰命名法(例如,UserProductCategory)。数据库表应该是复数的(例如,usersproduct_categories)。
  • 控制器:复数和驼峰命名法,以Controller结尾(例如,UsersControllerProductCategoriesController)。
  • 视图:组织成与控制器名称(复数)匹配的文件夹,文件名与操作名称匹配(例如,users/show.html.erb 表示 showUsersController 中的 code> 操作)。
  • 迁移:以时间戳为前缀并描述所采取的操作(例如,202401011230_add_email_to_users.rb)。

2. 控制器操作结构和命名

Rails 遵循 RESTful 约定,建议在适用的情况下使用七个标准操作:indexshownew、<代码>创建、编辑更新销毁。围绕资源构建控制器,并尽可能保持操作 RESTful,将每个操作集中在特定的 CRUD 操作上。

3. 在视图中渲染信息

  • 对部分使用render非常适合可重用组件(例如表单、页面的各个部分)。使用前导下划线命名部分 (_form.html.erb),并使用 render 'form'renderpart: 'form' 渲染它们。
  • 使用 :content_for 最适合从视图内将内容插入布局的特定区域,例如添加自定义标题或脚本。避免过度使用 content_for 来获取自然适合部分结构的内容。
  • 不推荐的做法:过度使用帮助程序方法来生成 HTML(导致混乱的帮助程序模块)并在视图中放置过多的逻辑(考虑将复杂的逻辑移至帮助程序或演示程序)。

4. 帮助程序

帮助程序用于与视图相关的方法,以保持视图代码的整洁和可读性。示例包括格式化日期、数字或字符串,以及生成表单组件或链接。避免将业务逻辑放入助手中;应驻留在模型或服务对象中。

5. 常见陷阱

  • 不遵循 RESTful 原则:导致控制器操作和路由混乱。
  • 胖模型或控制器:争取瘦控制器和模型;使用服务

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

  • Models: Singular and CamelCase (e.g., User, ProductCategory). Database tables should be pluralized (e.g., users, product_categories).
  • Controllers: Plural and CamelCase, ending in Controller (e.g., UsersController, ProductCategoriesController).
  • Views: Organized into folders matching controller names (plural), with file names matching action names (e.g., users/show.html.erb for the show action in UsersController).
  • Migrations: Prefixed with a timestamp and describe the action taken (e.g., 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, and destroy. Structure your controllers around resources and keep actions RESTful when possible, focusing each action on a specific CRUD operation.

3. Rendering Information in Views

  • Using 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 with render 'form' or render partial: 'form'.
  • Using :content_for: Best for inserting content into specific areas of a layout from within a view, like adding a custom title or scripts. Avoid overusing content_for for content that fits naturally into a partial structure.
  • Not Recommended Practices: Overusing helper methods for generating HTML (leads to cluttered helper modules) and placing too much logic in views (consider moving complex logic to helpers or presenters).

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

  • Not Following RESTful Principles: Leads to confusing controller actions and routes.
  • Fat Models or Controllers: Strive for skinny controllers and models; use service
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文