【发布时间】:2018-02-02 01:01:13
【问题描述】:
此问题源于:How to link form after creating rails join table
我正在我的产品和类别模型之间创建连接表。
连接表应该命名为什么? categories_products 或 category_products 还是别的什么?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 rails-migrations
此问题源于:How to link form after creating rails join table
我正在我的产品和类别模型之间创建连接表。
连接表应该命名为什么? categories_products 或 category_products 还是别的什么?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 rails-migrations
categories_products。都是复数。按词汇顺序。
除非连接表的名称通过使用 :join_table 选项,Active Record 通过使用 类名的词法顺序。所以客户和订单之间的连接 模型将给出默认连接表名称“customers_orders” 因为“c”在词汇排序中的排名高于“o”。
【讨论】:
CategoryProduct 怎么不自动拾取这张表?它似乎在寻找category_products。我必须指定self.table_name = "categories_products"
CategoryProduct 的模型与rails 为多对多计算的连接表名称不同。问题是关于连接表,而不是名为 CategoryProduct 的模型。
uuid作为你的表的主键,你需要在你的迁移中通过create_join_table(:products, :categories, column_options: {type: :uuid}) 明确指定它。来源:blog.bigbinary.com/2016/06/16/…
请注意,Rails 4 中有一些新规则。
指定与另一个类的多对多关系。这通过中间连接表关联两个类。除非连接表被明确指定为一个选项,否则它是使用类名的词法顺序来猜测的。因此,Developer 和 Project 之间的连接将给出默认连接表名称“developers_projects”,因为“D”按字母顺序位于“P”之前。
请注意,此优先级是使用
如果您的表共享一个公共前缀,则它只会在 开始。例如,表“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
【讨论】:
developer + project --> developer_projectspaper_box + paper --> paper_box_paperscatalog_category + catalog_product --> catalog_category_products
Project(单数,表名将是 projects)和单独的表,如 papers(复数,模型将是 Paper) - 两者都是正确的,只是来自不同的上下文.
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 迁移创建一个没有对应模型的连接表,因此模型名称不需要命名约定。
要访问连接,必须在两个表上声明 has_and_belongs_to_many,并通过创建的关联访问它们。
【讨论】: