Rails 连接表命名约定

问题描述 投票:0回答:4

这个问题源于:创建rails join表后如何链接表单

我正在我的

Product
Category
模型之间创建连接表。

连接表应该命名为什么:

categories_products
category_products
或其他名称?

ruby-on-rails join database-design naming-conventions
4个回答
79
投票

categories_products
。均为复数。按词汇顺序。

引用

除非使用显式指定连接表的名称 :join_table 选项,Active Record 通过使用创建名称 类名的词汇顺序。因此客户和订单之间的连接 模型将给出默认的连接表名称“customers_orders” 因为在词汇顺序上“c”的排名高于“o”。


55
投票

轨道4

请注意,从 Rails 4 开始,出现了一些新规则。

指定与另一个类的多对多关系。这通过中间连接表关联两个类。除非将连接表显式指定为选项,否则将使用类名的词汇顺序进行猜测。因此,Developer 和 Project 之间的联接将给出默认的联接表名称“developers_projects”,因为按字母顺序“D”位于“P”之前。

请注意,此优先级是使用 < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables “paper_boxes” and “papers” to generate a join table name of “papers_paper_boxes” because of the length of the name “paper_boxes”, but it in fact generates a join table name of “paper_boxes_papers”. Be aware of this caveat, and use the custom :join_table option if you need to.

计算的

如果您的表共享一个公共前缀,则它只会在页面中出现一次 开始。例如,表“catalog_categories”和 “catalog_products”生成一个连接表名称 “目录_类别_产品”。

=> Rails v4.2.7 文档

# alphabetically order
developers + projects                 -->  developers_projects 

# precedence is calculated with '<', lengthier strings have precedence 
# if the string are equal compared to the shortest length
paper_boxes + papers                  -->  paper_boxes_papers  

# common prefix omitted
catalog_categories + catalog_products -->  catalog_categories_products 

轨道5

规则还是一样的。在 Rails 5 中,我们有了一个新的助手,可以通过迁移创建连接表:

class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0]
  def change
    create_join_table :developers, :projects
  end
end

=> Rails 的 Edge 文档


3
投票

Rails 中的联接表必须仅按字母顺序创建。每次创建连接表时请记住这一点。

例如,如果您想在项目表和协作者表之间创建一个联接表,则必须如下命名。

语法:

first_table_name(UNDERSCORE)second_table_name

# Names must be in alphabetical order and also in plural
# Decide which is your first table name based on the alphabetical order

示例:创建项目和协作者之间的联接表

Collaborator-Project

collaborators_projects   
# you should name it  like this; In alphabetical order with plural names

示例 2: 在 BlogPost 表和 User 表之间创建联接表

BlogPost-User

blog_posts_users      # In alphabetical order with plural names

1
投票

新的create_join_table迁移创建一个没有对应模型的连接表,因此模型名称不需要命名约定。

要访问联接,您必须在两个表上声明 has_and_belongs_to_many,并通过创建的关联来访问它们。

© www.soinside.com 2019 - 2024. All rights reserved.