2010-11-19 14 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

これはどの言語ですか? –

+0

申し訳ありません。これはRuby on Rails向けです。 – odina

+0

テーブルの構造を教えてください。 。私は質問ではっきりしていません...あなたは自己参加をお探しですか? – Rakesh

答えて

0

ユーザーのコレクションではなく、接続のコレクションが必要ですか?

必要な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 

ないあなたが好きな、多分それはあなたにいくつかのアイデアをあげるほど便利。

関連する問題