Ruby on Rails 复数(控制器)和单数(模型)约定 - 解释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10078139/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:12:05  来源:igfitidea点击:

Ruby on Rails plural (controller) and singular (model) convention - explanation

ruby-on-railsrubyactiverecord

提问by

As per Ruby on Rails convention, controller names get pluralized while model names are singular. Example : a Users controller, but a User model.

根据 Ruby on Rails 约定,控制器名称采用复数形式,而模型名称采用单数形式。示例:一个用户控制器,但是一个用户模型。

rails generate controller Users
rails generate model User name:string email:string

Now open migration file

现在打开迁移文件

 class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email    
      t.timestamps
    end
  end
end

Here table name is plural (users).

这里表名是复数(用户)。

So my question is - Why table name is plural (users) even though the model name is singular (User)?

所以我的问题是 - 为什么表名是复数(用户),即使模型名称是单数(用户)?

采纳答案by AMIC MING

Ruby on Rails follow linguistic convention. That means a model represents a single user, whereas a database table consists of many users.

Ruby on Rails 遵循语言约定。这意味着模型代表单个用户,而数据库表由多个用户组成。

回答by Emily

An instance of your Usermodel represents a single user, so is singular. The userstable, by contrast, holds all of your users, so it's plural.

User模型的一个实例代表单个用户,因此是单数。users相比之下,该表包含您的所有用户,因此它是复数形式。

回答by Justin D.

To complete Emily's answer

完成艾米丽的回答

An instance of your User model represents a single user, so is singular. The users table, by contrast, holds all of your users, so it's plural.

您的 User 模型的实例代表单个用户,因此是单数。相比之下,users 表包含所有用户,因此它是复数形式。

回答by Ganesh Arulanantham

in rails conntroller and table name are plural model alone is singular.In a two word name second word is pluralized !

在 rails 控制器和表名称是复数模型单独是单数。在两个词名称中,第二个词是复数!

回答by John Paul Ashenfelter

Because the table holds users. Its just the convention.

因为该表包含用户。它只是公约。