influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.67k stars 463 forks source link

Unable to access current Tenant in Model #535

Closed shardulmohite closed 6 years ago

shardulmohite commented 6 years ago

Steps to reproduce

I am trying to access Apartment::Tenant.current inside the models and specifically to use with paperclip path for s3.

class asset
   has_attached_file :file,
                    :storage => :s3,
                    :s3_credentials => {
                      :access_key_id => "ACCESSKEY",
                      :secret_access_key => "SecreteKey"
                    },
                    :path => "#{Apartment::Tenant.current}/:class/:attachment/:id_partition/:style/:filename"
end

Expected behavior

Apartment::Tenant.current should return current tenant consistenantly.

Actual behavior

It dosnt return current tenant consistently. I have to restart the server to get the correct tenant

System configuration

Macbook Pro - latest version

shardulmohite commented 6 years ago

This was not the problem with Aparment gem, rather it was issue with how I was trying to use dynamic path of paperclip. I should have used paperclip.interpolates to generate dynamic path instead of using it inside the path directly.

Solution is :

change the path to

:path => ":tenant/:class/:attachment/:id_partition/:style/:filename"

and then add below to your paperclip.rb file

Paperclip.interpolates :tenant do |attachment, style|
  Apartment::Tenant.current
end