开发者

(Rails Question) Merging multiple polymorphic has_many relationships

(This is not the actual code I'm using, although this sums up the idea of what I want to do)

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

class User < ActiveRecord::Base
  has_many :followers开发者_Go百科, :class_name => 'Connection', :as => :connection1
  has_many :followings, :class_name => 'Connection', :as => :connection2
end

My question is that I want to know how I will be able to create a method called "network" such that what is returned isn't an array. Like so,

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

So that I'll still be able to do this:

u.network.find_by_last_name("James")

ETA:

Or hmm, I think my question really boils down to if it is possible to create a method that will merge 2 has_many associations in such a way that I can still call on its find_by methods.


Are you sure that you want a collection of Connections, rather than a collection of Users?

If it's a collection of Connections that you need, it seems like you'll be well served by a class method on Connection (or scope, if you like such things).

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

Probably not as useful as you'd like, but maybe it'll give you some ideas.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜