I have two tables with has_and_belongs_to_many relationship: categories
and raw_categories
Should the table be called categories_raw_categories
?
I have two tables with has_and_belongs_to_many relationship: categories
and raw_categories
Should the table be called 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.
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