-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Minor - P4
-
None
-
Affects Version/s: None
-
Component/s: Associations
-
None
Note
I don't consider this a super high priority, but it would be nice-to-have, especially to match what Rails SQL does.
Background
ActiveRecord's has_and_belongs_to_many (HABTM) works fundamentally different than Mongoid.
- In Mongoid, HABTM uses an array of foreign keys.
- In ActiveRecord, HABTM uses a join table. For example:
class Employee has_and_belongs_to_many :jobs, through: :employee_jobs end class EmployeeJob belongs_to :employee belongs_to :jobs end class Job has_and_belongs_to_many :employees, through: :employee_jobs end
In 95% of cases, the array foreign key way is better, however, it would still be useful if Mongoid could support the ActiveRecord-style join table HABTM.
Several reasons why:
- Document Size: Supposing that each employee has 1000+ jobs, and it means that each employee document will end up with a "job_ids" array with 1000 members. This creates document bloat.
- Metadata: It allows you to add metadata to the join table, e.g. you could add an "assignment_type" field to "employees_jobs".
- AR migratability: Currently I am migrating a legacy AR application to Mongoid, which uses join tables extensively. I'm using the Debezium connector to pipe SQL data into MongoDB, prefixing the collections with "raw_*", and it works brilliantly. The problem is the AR app contains lots of HABTMs, and its not easy to replicate in Mongoid.
HABTMs with join tables should be a relation like any other, and support eager loading, etc. In SQL, you can use the JOIN keyword to join on these intermediate tables; I'm not sure if the asset pipeline supports a similar thing.