DEV Community

Cover image for Rails ActionCable The Saga Continues
shakycode
shakycode

Posted on

Rails ActionCable The Saga Continues

Yesterday I wrote a post titled, “My Struggle With Rails ActionCable” which got a lot of good feedback and reviews. But overnight I thought long and hard about this problem that I faced in that I could not get the request origin aka TENANT to be delegated to the channel.rb file.

There was an open issue on the Apartment Gem where several people were discussing Apartment and Actioncable. After doing my own research and coming up short I saw a light at the end of the tunnel. One of the contributors to the Apartment gem found some documentation on how the user is verified for connection and he discovered the following in the documentation.

"Note that anything marked as an identifier will automatically create a delegate by the same name on any channel instances created off the connection."

So I went to work to refactor my code and this is what I came up with in the connection.rb file

connection.rb

If you notice the ActionCable connection is now identified by current_user and by tenant by setting the tenant in the connect method by simply calling self.tenant = request.subdomain then immediately following we switch the tenant and connect to the proper channel based on tenant. Since we are now delegating tenant to the channel it's a relatively easy fix to get the channel wired up and switch the tenant in our send_message method.

channel.rb

Now if you look at the send_message method in the channel file you'll notice we're switching the tenant as such Apartment::Tenant.switch!(tenant) which is possible now because we delegated tenant from the connection.rb file so that it's available to the channel.

End result, ActionCable and Multi-tenancy now working across the board. I honestly haven't seen a use case (trust me I've googled for hours) where someone was building a multi-tenant SaaS platform and integrating ActionCable.

So now this feature is near completion, just ironing out some coffeescript bugs and issues with the Background Job processor.

I'm hoping to write a full tutorial soon on this topic, but for now the problem is solved and I have to give a big thanks to the Apartment and Rails community for helping to steer me in the right direction to solve my specific use case.

What are you building with ActionCable? Are you implementing multi-tenancy? If so, give me a shout and let's compare notes!

Cheers!
shakycode ❤
Twitter: shakycode
Email: shakycode@gmail.com

Originally posted here

Top comments (1)

Collapse
 
shakycode profile image
shakycode

I'm glad you found it helpful. Sorry for the roller coaster of emotions. I've went from discouraged to happy to sad to ragecoding in 48 hours :) Thanks so much for reading and commenting! I write more at shakycode.com