多个数据库表的连接表在下面的代码中不起作用
class City < ActiveRecord::Base
establish_connection :cities_db
self.table_name_prefix = "cities_db."
has_many :clients
end
class Client < ActiveRecord::Base
# default connection
belongs_to :city
self.table_name = "client"
def self.with_cities
joins(:city)
end
end
Client.with_cities # returns ActiveRecord::StatementInvalid: Mysql2::Error: Table 'cities_db.clients' doesn't exist: SELECT `city_db`.`cities`.* FROM `cities_db`.`cities` INNER JOIN `clients` ON `clients`.`city_id` = `cities_db`.`cities`.`id`
答案 0 :(得分:3)
根本原因:设置table_name未设置table_name_prefix
Client.with_cities在以下的上下文中运行:cities_db connection。要修复它,请更改Client.rb
self.table_name = "client"
到
self.table_name = "#{self.connection.current_database}.client"