3

(这不是我正在使用的实际代码,尽管这总结了我想要做的事情)

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

我的问题是我想知道如何创建一个名为“network”的方法,以便返回的不是数组。像这样,

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

这样我仍然可以这样做:

u.network.find_by_last_name("James")

预计到达时间:

或者嗯,我认为我的问题真的可以归结为是否有可能创建一个方法来合并 2 个 has_many 关联,这样我仍然可以调用它的 find_by 方法。

4

1 回答 1

0

你确定你想要一个连接集合,而不是一个用户集合吗?

如果它是您需要的 Connections 的集合,那么 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

用户.rb

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

可能没有你想的那么有用,但也许它会给你一些想法。

于 2010-11-24T19:18:49.270 回答