简体   繁体   中英

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.

This is sort of a has_many self join and a many_to_many self join.

I need to be able to type @user.subscribers and @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 .

I have seen Ryan Bates Railscast on Self-Referential Associations . However that creates 1 way self-joins. 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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