在这种情况下,Rails 3.1 中的连接表会调用什么? [英] What would the joining table called in this case in Rails 3.1?

查看:41
本文介绍了在这种情况下,Rails 3.1 中的连接表会调用什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有 has_and_belongs_to_many 关系的表:categoriesraw_categories

I have two tables with has_and_belongs_to_many relationship: categories and raw_categories

表格应该叫categories_raw_categories吗?

Should the table be called categories_raw_categories?

推荐答案

是的,连接表是根据要连接的两个表按字母顺序命名的.由于categories 在字母表中的位置高于raw_categories,因此连接表称为categories_raw_categories.注意,如果你在做迁移,你需要为这个连接表创建一个单独的迁移.

Yes, the join table is named after the two tables to be joined listed in alphabetical order. Since categories is higher in the alphabet than raw_categories, the join table is called categories_raw_categories. Note that if you are doing migrations, you need to create a separate migration for this join table.

有关 HABTM 关系及其所需连接表的更多详细信息,请参见此处:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

See here for more details on HABTM relationships and the join tables required for them: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

另请注意,您可以根据需要为连接表设置自定义名称.示例(如果要调用连接表category_associations):

Also note that you can set a custom name for the join table if you want. Example (if you want to call the join table category_associations):

# Category model
has_and_belongs_to_many :raw_categories, :join_table => 'category_associations'

# RawCategory model
has_and_belongs_to_many :categories, :join_table => 'category_associations'

您也可以始终通过在要连接的模型上使用 has_many :though 来显式地使连接表成为一流模型.按照上面的例子,你可以让 CategoryAssociation 成为一个实际的模型,然后像这样将它加入到其他两个模型中:

You can also always explicitly make the join table a first-class model by using has_many :though on the models to be joined. Following the example above, you could make CategoryAssociation an actual model and join it to the other two like this:

# CateogoryAssociation model
belongs_to :category
belongs_to :raw_category

# Category model
has_many :category_associations
has_many :raw_categories, :through => :category_associations

# RawCategory model
has_many :category_associations
has_many :categories, :through => :category_associations

这篇关于在这种情况下,Rails 3.1 中的连接表会调用什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆