This is a stupid fucking thing, but here we are. My underling and I wasted 40 minutes today re-figuring this out.
Migration:
class PluralSingular < ActiveRecord::Migration[5.0]
create_join_table :plural, :plural
end
Model:
app/model/foo.rb
class Foo < ApplicationRecord
has_many :plural_singular
has_many :plural, through: :plural_singular
end
Join model:
app/model/plural_singular.rb
class PluralSingular < ApplicationRecord
belongs_to :foo
belongs_to :bar
end
Harry #
It is a stupid thing but I thank you dearly for making this blog post
Chris #
Hi Mark,
Thanks for the this, our team was just debating join models as SingularSingular or PluralSingular and I ran across your post. Curious what drove you to decide that PluralSingular is the correct way? Will we miss out on some ActiveRecord magic by using the SingularSingular class name pattern on our join model?
Mark Grealish #
Hey Chris, it’s as simple as that’s the Ruby on Rails convention when you don’t give a join table a special name.
Travis Smith #
This post has saved my sanity more times than I can count in the past 6 months. Thank you kindly.
John #
Current (6/19) Rails Guide implies
PluralPlural
:The migration method
create_join_table
creates an HABTM (has and belongs to many) join table. A typical use would be:create_join_table :products, :categories
which creates a
categories_products
table with two columns calledcategory_id
andproduct_id
.See: https://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-join-table
John #
woops…disregard previous comment!