DAddYE/mini_record

has_and_belongs_to_many join table name issues

burnt43 opened this issue · 1 comments

Lets say I have 2 classes

class SchoolTeacher < ActiveRecord::Base
  self.table_name = 'school_teachers_foo'
  field :name
  has_and_belongs_to_many :school_students
end

class SchoolStudent < ActiveRecord::Base
  self.table_name='school_students_foo'
  field :name
  has_and_belongs_to_many :school_teachers
end

If I were to auto_upgrade on the SchoolStudent class for instance

SchoolStudent.auto_upgrade!

It creates a join_table 'school_students_foo_school_teachers'
[MiniRecord] Creating Join Table school_students_foo_school_teachers with keys school_student_id

However, Rails 4 does not look for a table with the same name

SchoolStudent.create(name: 'James')
SchoolStudent.first.school_teachers
irb(main):015:0> SchoolStudent.first.school_teachers
Mysql2::Error: Table 'hpbx_development.school_students_foo_teachers_foo' doesn't exist: SHOW FULL FIELDS FROM `school_students_foo_teachers_foo`
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'hpbx_development.school_students_foo_teachers_foo' doesn't exist: SHOW FULL FIELDS FROM `school_students_foo_teachers_foo`

To summarize

  • mini_record creates 'school_students_foo_school_teachers'
  • activerecord looks for 'school_students_foo_teachers_foo'

There are 2 issues with mini_record join table naming convention

  1. It does not take into account prefixes (school in my example's case)
  2. It does not use the table_name for the association, it only uses the association name (school_teachers vs school_teachers_foo)

I understand I can change the join_table option when defining the has_and_belongs_to_many relationship, but I'd like to not have to set this option if I don't have to.

I don't know if anyone is interested, but I am going to work on a PR for this.

PR complete. #54