Map ActiveRecord to external database


#1

Hi, Im writing a Plugin for redmine. My Problem is to map an
ActiveRecord to an external database. Here’s my class:


class FtpUser < ActiveRecord::Base
attr_accessor :created_at, :password;
attr_writer :uid, :gid;
attr_reader :user, :dir;

establish_connection(
:adapter => Setting.plugin_users[‘db_adapter’],
:host => Setting.plugin_users[‘db_host’],
:user => Setting.plugin_users[‘db_user’],
:password => Setting.plugin_users[‘db_password’],
:database => Setting.plugin_users[‘db_database’],
:port => Setting.plugin_users[‘db_port’]
)

self.table_name=‘users’

self.primary_key=‘user’

def initialize(params={})
if (params.include? :set_password && params[:set_password] == true)
self.password=generateRandomPassword(10)
end
@user = ‘c’ + (self.id.to_int + 1000).to_s
@dir="/var/ftp/#{user}"
@created_at=DateTime.now
@uid=2001;
@gid=2001;
end


end

When I call my class with the Controller like in this case:

class UsersController < ApplicationController

def index
User.establish_connection #!!!
@users=getActiveUsers
end

private

def getActiveUsers
time=30.days.ago.beginning_of_day
@users=User.where(‘created_at >= ?’, time.to_datetime)
end

end

the function ‘where’ is using the default database and not the database
which is set in the ‘establish_connection’-Function. How can I change
this problem. Hope someone can help me. With best regards, Daniel.

PS. ‘user’ is not really the classname :-). It’s a place holder.


#2

Here is a good link which solved my problem:
http://ilikestuffblog.com/2012/09/21/establishing-a-connection-to-a-non-default-database-in-rails-3-2-2/