2010-06-14 48 views
2

我正在使用外部用戶數據庫來處理不同的項目。在rails項目中使用兩個或多個數據庫

現在我已經在我的項目中獲得了學校模型,其has_many用戶和用戶有很多學校。

class User < ActiveRecord::Base 
    establish_connection "#{RAILS_ENV}_tunnel" 
    has_many :memberships 
    has_many :schools, :through => :memberships 
end 

class School < ActiveRecord::Base 
    has_many :memberships 
    has_many :users, :through => :memberships 
end 

class Membership < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :school 
end 

所以我現在有什麼樣的問題:

  • 我不能叫school.users(因爲成員關係表是在我的項目數據庫,而不是在exernal USERS分貝),但我可以調用用戶.schools
  • 我無法以這種方式更新:current_user.school.find(params [:id])。update_attributes(params [:school]),因爲它以這種方式打開READ ONLY連接。

我明白,我怎麼能砍這個問題,即

school.users我可以這樣調用:

class School < ActiveRecord::Base 
    has_many :memberships 
    # has_many :users, :through => :memberships 

    def users 
    User.where("users.id in (?)", self.connections.map(&:user_id)) 
    end 
end 

但這黑客是不夠的。因爲現在我無法添加像school.users << User.find(203)school.users.find(params[:user_id])等其他功能的用戶,該has_many關係給了我。

因此問題是如何使用兩個數據庫進行操作,這兩個數據庫通過多對多的關係連接到全功能支持。

回答

3

我不認爲這是在Rails的全功能支持這樣做的方式 - 我認爲你最好嘗試使用類似MySQL's federated tables帶來的遠程數據庫表到您的生產數據庫。

+0

+1這聽起來像是一個更簡單的解決方案,頭痛的可能性較小。 – Jeriko 2010-06-14 12:58:43

+0

很有意思。但是,源和我的表副本同步速度有多快? – fl00r 2010-06-14 14:20:45

+1

@ fl00r - 它不是表的副本 - 它是與其他數據庫的直接連接,所以同步不是問題。 – Codebeef 2010-06-19 14:13:54

0

在oracle中,我將爲此使用數據庫鏈接。

我不能完全肯定,但我發現,在MySQL中,你可以寫

select * from db1.users , db2.schools where db1.users.school_id = db2.schools.id 

,那麼你將能夠使用到使用Rails中通過在模型中明確寫明表名:

class School 
    set_table_name "db2.schools" 
end 

這有幫助嗎?

+0

看起來很有趣,我會盡快檢查,謝謝! – fl00r 2010-06-15 20:30:17

相關問題