简体   繁体   English

HABTM或HM / HMT自加入Rails

[英]HABTM or HM/HMT Self-Join in Rails

I have a Users model and want users to be able to Subscribe to another User to get notifications when they post things. 我有一个Users模型,希望用户能够Subscribe其他User ,以便在发布内容时收到通知。

This is sort of a has_many self join and a many_to_many self join. 这有点像has_many自连接和many_to_many自连接。

I need to be able to type @user.subscribers and @user.subscriptions . 我需要能够输入@user.subscribers@user.subscriptions

So, the relationship in one sense is both ways by default. 因此,默认情况下,这种关系在某种意义上是两种方式。 However, if @user1 subscribes to @user2 , that does not mean @user2 is subscribed to @user1 howevver, @user2 can find @user1 via @user.subscribers . 但是,如果@user1 subscribes @user2 ,这并不意味着@user2 subscribed @user1 howevver, @user2可以通过@user.subscribers找到@user1

I have seen Ryan Bates Railscast on Self-Referential Associations . 我见过Ryan Bates 关于自我指导协会的Railscast However that creates 1 way self-joins. 然而,这创造了1种方式的自连接。 But I think that doesn't leave the fact that there can be two relationships between the parties. 但我认为这并不意味着双方之间可能存在两种关系。

However, I have also seen The Rails Guide on association foreign keys. 但是,我也看过关于外键的Rails指南。

I realize I could probably the Ryan Bates way, and just build two relationships, but that seems wrong, but I fear that the second way won't allow one to be a subscriber and one to be a provider each way. 我意识到我可能是Ryan Bates的方式,只是建立两种关系,但这似乎是错误的,但我担心第二种方式不允许一个人成为订阅者而一个人成为提供者。 What is the most "correct" way to go about this? 最正确的方法是什么?

Don't over complicate things 不要过于复杂化

class Subs < ActiveRecord::Base

    belongs_to :subscriber, :class_name => 'User'
    belongs_to :user

end

class User < ActiveRecord::Base

    has_many :subs
    has_many :subscribers, :through => :subs, :source => :subscriber
    has_many :subscriptions, :through => :subs, :source => :user
end

Obviously you have to set up the join model in your database. 显然,您必须在数据库中设置连接模型。 And that should do it. 这应该做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM