Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"should have_and_belong_to_many" produces incorrect joined table name when overriding ActiveRecord::Base#table_name_prefix #1210

Open
kayla-glick opened this issue May 23, 2019 · 0 comments

Comments

@kayla-glick
Copy link

Context

I have two models that are joined by a has_and_belongs_to_many relationship

# app/models/foo.rb
class Foo < ApplicationRecord
  has_and_belongs_to_many :bars
end
# app/models/bar.rb
class Bar < ApplicationRecord
  has_and_belongs_to_many :foos
end

And an additional class that overrides ActiveRecord::Base#table_name_prefix in order to allow us to join associations between this application and another application that heavily relies on this one to generate some reports comparing data between the two applications.

# app/models/application_record.rb

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def self.table_name_prefix
    Rails.configuration.database_configuration[Rails.env]['database'] + '.'
  end
end

Using the joined table association between foos and bars (foos_bars) produces the correct joined table in our queries:

`our-database`.`foos_bars`

Issue

We have an existing model spec for the Foo model that checks that the has_and_belongs_to_many association exists which is now failing after overriding the self.table_name_prefix method.

RSpec.describe Foo, type: :model do
  it { should have_and_belong_to_many :bars }
end

Expected Foo to have a has_and_belongs_to_many association called bars (join table our-database_test.foos_database.bars doesn't exist)

As you can see, the table name that shoulda_matchers expects is incorrect. It should be expecting our-database_test.foos_bars.

I have already confirmed that Rails produces the correct joined table name so I believe this is a shoulda_matchers bug.

@kayla-glick kayla-glick changed the title "should have_and_belong_to_many" produces incorrect joined table when overriding ActiveRecord::Base#table_name_prefix "should have_and_belong_to_many" produces incorrect joined table name when overriding ActiveRecord::Base#table_name_prefix May 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants