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

[Rails 6] Advice for injecting manual connection switching for unsubscribe GET route #55

Closed
rromanchuk opened this issue Aug 1, 2020 · 2 comments

Comments

@rromanchuk
Copy link

https://edgeguides.rubyonrails.org/active_record_multiple_databases.html#using-manual-connection-switching

Using Rails 6 multiple database support, the GET request attempts to use the reader role which then fails. Thinking about what the cleanest approach to wrapping opt_out(options) inside of a ActiveRecord::Base.connected_to(role: :writing) block. Right now i'm just monkey patching the controller action.

Similar issues in other gems heartcombo/devise#5133

@ankane
Copy link
Owner

ankane commented Aug 2, 2020

Hey @rromanchuk, you should be able to add an around_action for the controller in an initializer. Something like:

Mailkick::SubscriptionsController.around_action do
  ActiveRecord::Base.connected_to(role: :writing) do
    yield
  end
end

Another approach could be customizing the resolver to exclude Mailkick paths.

The automatic connection switching feature is opt-in and pretty basic right now (by design), so I don't think it make sense to add official support for it.

@ankane ankane closed this as completed Aug 18, 2020
@kevinzwhuang
Copy link

For anyone reading this and adding an around_action to an initializer, I found that this works:

# config/initializers/mailkick.rb

Mailkick::SubscriptionsController.around_action do |_controller, action|
  ActiveRecord::Base.connected_to(role: :writing) do
    action.call
  end
end

This is because calling around_action inline does not make yield available.
The Rails docs explain that using around_action directly this way gives a controller and an action argument to the block. We can use the action block to yield.

Rails docs explanation: https://guides.rubyonrails.org/action_controller_overview.html#other-ways-to-use-filters
Rails GitHub issue that explains this in more detail: rails/rails#37616

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants