(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")
预计到达时间:
或者嗯,我认为我的问题实际上归结为是否可以创建一个方法来合并 2 个 has_many 关联,以便我仍然可以调用其 find_by 方法。
(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, :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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确定需要连接的集合,而不是用户的集合吗?
如果它是您需要的 Connections 集合,似乎 Connection 上的类方法(或范围,如果您喜欢这样的东西)会很好地为您服务。
connection.rb
user.rb
可能没有您想要的那么有用,但也许它会给您一些想法。
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
user.rb
Probably not as useful as you'd like, but maybe it'll give you some ideas.