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?

5
  • I think you're trying to build a multi tenant app. This is quite complicated thing to do for a newbie ;) Commented Sep 1, 2014 at 16:28
  • well aren we all newbies in something :) i learn when I push myself to the limit.It may be a bad approach but I learn the best in that way.Thanks for the heads up tho Commented Sep 1, 2014 at 16:41
  • This looks relevant stackoverflow.com/questions/1298909/… Commented Sep 1, 2014 at 16:43
  • I just wanted to make a friendly joke about your nickname Commented Sep 1, 2014 at 18:11
  • @MichalSzyndel i noticed man :) Commented Sep 1, 2014 at 18:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.