Multiple Active Record Connection


#1

Dear all

My ActiveRecord::Base is connected to server_a (local server), has a
Server model contains about 100 server records (remote server).

I use the following block to retrieve the server infomation. It works
fine.

Server.find_all_by_server_type(“sybase_t”).each do |s|

if s.server_name =~ /^LIS_..._ST1[0-2]/ and s.is_active?
  class Order < ActiveRecord::Base
    set_table_name = "orders"
  end
  Order.establish_connection s.connection_hash

  begin
    puts "#{s.server_name} has #{Order.count} orders"
  rescue
    puts "#{s.server_name} is down"
  end

end

end

I want to create another model OrderDetail in the remote server (see
below code). It does not work. It said “TypeError: superclass mismatch
for class OrderDetail”.

Server.find_all_by_server_type(“sybase_t”).each do |s|
if s.server_name =~ /^LIS_…_ST1[0-2]/ and s.is_active?
class Order < ActiveRecord::Base
set_table_name = “orders”
end
Order.establish_connection s.connection_hash
class OrderDetail < ActiveRecord::Base
set_table_name = “order_detail”
end
OrderDetail.establish_connection s.connection_hash
begin
puts “#{s.server_name} has #{Order.count} orders and
#{OrderDetail.count} order_detail”
rescue
puts “#{s.server_name} is down”
end
end
end

I used google and find that the error will happen if the code like this
http://railsforum.com/viewtopic.php?id=10993

  1. class Cool
  2. end
  3. class SpecialCool < Cool
  4. end
  5. class SpecialCool # this line will raise an error
  6. end

How can I change my code so that I can have more than 1 models in the
remote server?

Thank you very much
Valentino


#2

The error that you found in railsforum is probably on the right track.
Is there any other declaration of the class OrderDetail other than
what you have shown? If so, this is the problem. Also, if all of the
servers in you server model have the same set of models, you may want
to consider the following:

  1. Create a RemoteModel class that inherits from ActiveRecord. This
    class will only be used for inheritance and to simplify connections.
  2. Create “local” models for each model in the remote server. In your
    example, this would mean creating an order.rb and an order_details.rb
  3. Each of the models created in step 2 should inherit from
    RemoteModel. From your example

class Order < RemoteModel
end

  1. Your code can then look like this

Server.find_all_by_server_type(“sybase_t”).each do |s|
if s.server_name =~ /^LIS_…_ST1[0-2]/ and s.is_active?
RemoteModel. establish_connection s.connection_hash
# Do remote model stuff here
end
end

This approach DRY’s up your code and kinda puts things where they
belong.

On Mar 10, 10:19 am, Valentino L. removed_email_address@domain.invalid