0

i m using mysql2 as database and devise for user authentication.

before_action :authenticate_partner!

I have this line in my application_controller.rb as devise gem suggested.

I have total of 6 tables.

2 of them is in my default database and one of them partner table- created by devise.

What i want is this; when user_signed_in? returns true I want to establish a new connection based on the user name.

I got multiple controllers and I didn't want to create a establish_connection method for each one of them.

So how can I keep my user safe and use different databases?

class ApplicationController < ActionController::Base
  before_action :authenticate_partner!
  protect_from_forgery with: :exception

  def find_user_name
     if partner_signed_in?
       ActiveRecord::Base.establish_connection(                                                                                                                                    
         :adapter => "mysql2",                                                                                                                                                       
         :database => "db_#{current_partner.name} "
       )
    else
      logger.info "log in not succesful"
    end
  end
end

This code obviously gives me error when i remove def find_user_name but i can't seem to get in either of the if statements ( checked with logger.info)

So what should I do?

Mike Szyndel
  • 10,461
  • 10
  • 47
  • 63
railsnewbie
  • 161
  • 1
  • 10

1 Answers1

1

You can use remove_connection

old_connection = ActiveRecord::Base.remove_connection

If you have done

new_connection = ActiveRecord::Base.establish_connection(...)

This can be passed on to remove_connection

old_connection = ActiveRecord::Base.remove_connection(new_connection)

for detail code.

Anil Yadav
  • 1,086
  • 7
  • 18