What would the joining table called in this case in Rails 3.1?

北慕城南 提交于 2019-12-10 17:28:32

问题


I have two tables with has_and_belongs_to_many relationship: categories and raw_categories

Should the table be called categories_raw_categories?


回答1:


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.

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

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'

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


来源:https://stackoverflow.com/questions/8293336/what-would-the-joining-table-called-in-this-case-in-rails-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!