Ruby 关于连接其它数据库的配置

hxh1246996371 · 2015年09月13日 · 最后由 hxh1246996371 回复于 2015年09月13日 · 1833 次阅读

项目中我们需要引用到合作伙伴的一个表,所以我单独配置了模型,这是其中一个

class ApmSellMem < ActiveRecord::Base 
  ActiveRecord::Base.establish_connection Rails.application.config.kexin_db
  self.table_name = "mems"
  {
    :my_age=> :age,
    :my_name=> :name
  }.each do |k,v|
    send :alias_attribute,k,v
  end
end

现在我想把公共的部分提出来,只在每个模型中配置映射的表名和字段名即可,不知道有没有什么好方法。

我尝试在 application.rb 中写了一个 module

module KexinDb
  include ActiveRecord::ConnectionHandling
  ActiveRecord::Base.establish_connection Rails.application.config.kexin_db
end

但是没有起作用

# app/models/kexin_db_base.rb
class KexinDbBase < ActiveRecord::Base
    self.abstract_class = true
   ActiveRecord::Base.establish_connection Rails.application.config.kexin_db
end
# app/models/apm_sell_mem.rb
class ApmSellMem < KexinDbBase
   self.table_name = "mems"
   {
      :my_age=> :age,
      :my_name=> :name
   }.each do |k,v|
     alias_attribute k, v
  end
  .....
end

#2 楼 @fumesy 感谢,可以走通了

我改造了一下 kexin_db_base.rb

class KexinDbBase < ActiveRecord::Base
  self.abstract_class = true
  ActiveRecord::Base.establish_connection Rails.application.config.kexin_db

  def self.config settings
    self.table_name = settings[:table]
    settings[:fields].each do |k,v|
      send :alias_attribute,k,v
    end
  end
end

apm_sell_mem.rb

class ApmSellMem < KexinDbBase
  config({
    :table => "mems",
    :fields=> {
      :my_age=> :age,
      :my_name=> :name
    }
  })
end

#4 楼 @hxh1246996371 🆒 不过在 ActiveRecord::Base 中有一些 configurationsconnection_config 等方法,如定config 方法容易引起理解歧义,建议定义类似 kexin_config 这样感觉好些。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号