2010-11-19 63 views
3

(這不是我用實際的代碼,雖然這總結了什麼,我想要做的想法)(Rails的問題)合併多個多態性的has_many關係

class Connection < ActiveRecord::Base 
    belongs_to :connection1, :polymorphic => true 
    belongs_to :connection2, :polymorphic => true 
end 

class User < ActiveRecord::Base 
    has_many :followers, :class_name => 'Connection', :as => :connection1 
    has_many :followings, :class_name => 'Connection', :as => :connection2 
end 

我的問題是,我想了解我將如何創建一個名爲「網絡」的方法,以便返回的內容不是數組。像這樣,

u = User.first 
u.network # this will return a merged version of :followings and :followers 

所以,我還是可以做到這一點:

u.network.find_by_last_name("James") 

ETA:

或者嗯,我想我的問題其實歸結到是否有可能創建一個合併2個has_many關聯的方法,這樣我仍然可以調用它的find_by方法。

+0

這是什麼語言? – 2010-11-19 08:26:15

+0

哎呀,對不起。這是針對Ruby on Rails的。 – odina 2010-11-19 08:28:08

+0

你能否提供表格結構? 。我對這個問題不是很清楚......你在尋找一個自我加入嗎? – Rakesh 2010-11-19 10:09:57

回答

0

您確定需要Connections的集合,而不是用戶集合嗎?

如果它是您需要的Connections集合,那麼好像在Connection(或範圍,如果您喜歡這樣的事情)上可以很好地使用類方法。

connection.rb

class Connection < ActiveRecord::Base 
    class << self 
    def associated_with_model_id(model, model_id) 
     include([:connection1, :connection2]). 
     where("(connection1_type IS #{model} AND connection1_id IS #{model_id}) 
      OR (connection2_type IS #{model} AND connection2_id IS #{model_id})") 
    end 
    end 
end 

user.rb

class User < ActiveRecord::Base 
    def network 
    Connection.associated_with_model_id(self.class.to_s, id) 
    end 
end 

大概不會有用,因爲你想,但也許會給你一些想法。