ruby-on-rails - (Rails 问题)合并多个多态 has_many 关系

标签 ruby-on-rails polymorphism 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")

预计到达时间:

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

最佳答案

您确定要连接的集合而不是用户的集合吗?

如果它是您需要的 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

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

关于ruby-on-rails - (Rails 问题)合并多个多态 has_many 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4223201/

相关文章:

html - 导航的CSS问题

haskell多态函数评估错误

c++ - 使用基类的类型特征

ruby-on-rails - 如何在 Rails 中创建 "two-side"多对多关系?

ruby-on-rails - 在 `find_or_create_by` `has_many` 关联上使用 `through` 时出错

javascript - 应该如何在 React 类中编写函数?

html - Chrome 用户代理样式表覆盖我的网站样式

ruby-on-rails - 回形针 S3 default_url

java - 没有 Java 味道的多态性的正确实现

ruby-on-rails - 如何在 has_many 的情况下通过 : association? 验证关联记录的存在