这个问题源于:创建rails连接表后如何链接表单
我正在我的产品和类别模型之间创建连接表。
连接表应该命名为什么?categories_products 或 category_products 还是别的什么?
这个问题源于:创建rails连接表后如何链接表单
我正在我的产品和类别模型之间创建连接表。
连接表应该命名为什么?categories_products 或 category_products 还是别的什么?
categories_products
. 都是复数。按词汇顺序。
报价:
除非使用 :join_table 选项明确指定连接表的名称,否则 Active Record 会使用类名的词法顺序创建名称。因此,客户模型和订单模型之间的连接将给出默认的连接表名称“customers_orders”,因为“c”在词法排序中优于“o”。
请注意,Rails 4中有一些新规则。
指定与另一个类的多对多关系。这通过中间连接表关联两个类。除非连接表被明确指定为一个选项,否则它是使用类名的词法顺序来猜测的。因此,Developer 和 Project 之间的连接将给出默认连接表名称“developers_projects”,因为“D”按字母顺序位于“P”之前。
请注意,此优先级是使用字符串的 < 运算符计算的。这意味着如果字符串的长度不同,并且在与最短长度相比时字符串相等,则认为较长的字符串比较短的字符串具有更高的词汇优先级。例如,由于名称“paper_boxes”的长度,我们希望表“paper_boxes”和“papers”生成连接表名称“papers_paper_boxes”,但实际上它生成的连接表名称“paper_boxes_papers”。请注意此警告,并在需要时使用自定义 :join_table 选项。
如果您的表共享一个公共前缀,则它只会在开头出现一次。例如,表“catalog_categories”和“catalog_products”生成连接表名称“catalog_categories_products”。
# 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
规则还是差不多的。在Rails 5中,我们有一个新的助手来创建带有迁移的连接表:
class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0]
def change
create_join_table :developers, :projects
end
end
=> Rails 的边缘文档
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 表和用户表之间创建连接表
BlogPost-User
blog_posts_users # In alphabetical order with plural names
新的 create_join_table 迁移创建了一个没有对应模型的连接表,因此模型名称不需要命名约定。
To access the join, you must declare has_and_belongs_to_many on the two tables, and access them through the association created.