-
Notifications
You must be signed in to change notification settings - Fork 461
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
wrong ActiveRecord.sequence_name after switch tenant #508
Comments
Same problem here on a Rails 4.2.x app. Added this hackish piece of code to initializers/apartment.rb which does the job but is less than ideal: module PostgresqlSequenceResetter
def connect_to_new(tenant=nil)
super
model_names = ActiveRecord::Base.descendants.map(&:to_s)
tables = ActiveRecord::Base.connection.tables
.map(&:singularize)
.map(&:camelize)
resettable_tables = tables & model_names
resettable_tables.each do |table|
table.constantize.reset_sequence_name
end
end
end
require "apartment/adapters/postgresql_adapter"
Apartment::Adapters::PostgresqlSchemaAdapter.prepend PostgresqlSequenceResetter |
I would not recommend to use the answer from @caifara since it will just kill your application if it has 50+ models. The issue is that you will perform COUNT_OF_MODELS requests to database to reset sequences on each tenant switch. For my application with 180 models it was not a good idea. You can achieve the same result in much easier way: config/application.rb
This way your database will search for sequence in current tenant and then in public tenant (or in the way you configured the search path). |
@FUT thank you for your solution but there is a bug in it. If you update rake task following way:
it will show that after switching to the public schema it does not update a sequence name properly. I updated it a little + changed it to use tenant after switch hook. Put it to
|
The solution by @madzhuga will not work if you have models excluded from tenant. Currently I'm relying on an implementation detail of Rails, to avoid N database trips and this problem: ActiveRecord::Base.descendants.select{|c| c.instance_variable_defined?(:@sequence_name) }.each do |c|
c.remove_instance_variable :@sequence_name unless c.instance_variable_defined?(:@explicit_sequence_name) && c.instance_variable_get(:@explicit_sequence_name)
end Yuck, I know 😉 |
Steps to reproduce
source code:
test.rake
Book
tenant
Expected behavior
output of
rails dev:test
is:Actual behavior
output of
rails dev:test
is:System configuration
PostgresSQL9.6.6, compiled by Visual C++ build 1800, 64 bit
apartment (2.0.0)
config/initializers/apartment.rb
or so):use_schemas
: (true
orfalse
)true
Rails (or ActiveRecord) version:
5.1.0
Ruby version:
2.4.2
The text was updated successfully, but these errors were encountered: