4

I have two tables with has_and_belongs_to_many relationship: categories and raw_categories

Should the table be called categories_raw_categories?

Jacob
  • 6,317
  • 10
  • 40
  • 58
  • i always get confused by this, so what i do is a small test, fire up irb and type this - "categories" < "categories_raw_posts", if response is true, then the name of the join is "categories_raw_categories", if false, then its the reverse. Simple, but effective. This is because rails/ruby compares in lexical order of preference. – Hishalv Nov 28 '11 at 09:12
  • 1
    `has_and_belongs_to` is confusing..I would use `has_many :through` rather.. – rubyprince Nov 28 '11 at 10:00

1 Answers1

4

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
Ben Lee
  • 52,489
  • 13
  • 125
  • 145