Bidirectional Self-Relational Associations

Taking Ryan Bates ascicast as an example: http://asciicasts.com/episodes/163-self-referential-association

It ends with two user associations

  • : friends
  • : inverse_friends

Given that the user would not care who initiated the friendship, you need a user association that just was

  • : friends

which consisted of both relationships. ie Relationships provoked by the user and relationships initiated by the user-user.

So how can you achieve this bi-directional self-referential association?

UPDATE - Josh Susser has a post about this here: http://blog.hasmanythrough.com/2006/4/21/self-referential-through

However, he still talks about has_many: sources and has_many: sinking when there really should be has_many: nodes that include both sources and receivers.

+4
source share
1 answer

see if this works for you?

class User < ActiveRecord::Base has_many :friendships, :foreign_key => "person_id", :class_name => "Friendship" has_many :friends, :through => :friendships def befriend(user) # TODO: put in check that association does not exist self.friends << user user.friends << self end end class Friendship < ActiveRecord::Base belongs_to :person, :foreign_key => "person_id", :class_name => "User" belongs_to :friend, :foreign_key => "friend_id", :class_name => "User" end # Usage jack = User.find_by_first_name("Jack") jill = User.find_by_first_name("Jill") jack.befriend(jill) jack.friends.each do |friend| puts friend.first_name end # => Jill jill.friends.each do |friend| puts friend.first_name end # => Jack 

this sets the database table schema

 users - id - first_name - etc... friendships - id - person_id - friend_id 
+8
source

Source: https://habr.com/ru/post/1311122/


All Articles