0

I have models with many-to-many association for example User & Role which connected through RoleAssignment

table in DB1:

users
role_assignments

table in DB2:

roles

I can access user in DB1 with role_one.users, but i cannot access roles in DB2 with user_one.roles. It gives an exception

ActiveRecord::StatementInvalid: Mysql2::Error: Table 'db2_development.role_assignments' doesn't exist: 
SELECT `roles`.* FROM `roles` INNER JOIN `role_assignments` ON `roles`.`id` = `role_assignments`.`role_id` 
WHERE `role_assignments`.`user_id` = 1

Does anyone know how to access roles from user, or how to let rails know that role_assignments reside in DB1 not in DB2? thx

raymondralibi
  • 1,933
  • 1
  • 17
  • 25

2 Answers2

1

Solved my problem using table_name_prefix as shown at http://emphaticsolutions.com/2009/11/23/has_many_through_across_databases.html

class ActiveRecord::Base
  def self.table_name_prefix
    "app_name_development."
  end
end

class ExternalActiveRecord < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "external_development"

  def self.table_name_prefix
    "external_app_name_development."
  end
end

then

class Role< ExternalActiveRecord
  ...
end

and

class User < ActiveRecord::Base
  ...
end
raymondralibi
  • 1,933
  • 1
  • 17
  • 25
0

I havent done it myself, but you can subclass activerecord to maintain multiple db connections. See this blog post:

http://www.messaliberty.com/2009/02/ruby-how-to-use-multiple-databases-with-activerecord/

DVG
  • 17,392
  • 7
  • 61
  • 88
  • I have connected with multiple databases. Actually, i've already solved my quetion with [st-elsewhere](https://github.com/briandoll/st-elsewhere). Now i have a new problem, I try to connect User n Role with role_alias_assignments, i cannot access roles using alias for example: `has_many_elsewhere :role_aliases, source: :role, through: :role_alias_assignments`. it gives an error `undefined method `role_aliases' for #` – raymondralibi May 17 '12 at 12:04