gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:12:33 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com