Bidirectional self referential associations

Taking Ryan Bates' asciicast as an example:

He ends with two associations of User

  • :friends
  • :inverse_friends

Given that a user would not care who instigated the friendship, you would want a User association that was simply

  • :friends

that consisted of both relationships. i.e Relationships instigated by the user and relationships instigated by the user's friend.

So how can you achieve this bidirectional self-referential association?

UPDATE - Josh Susser has a post about this here:

However, it still talks about has_many :sources and has_many :sinks when really there should be a has_many :nodes that includes both the sources and the sinks.


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

class Friendship < ActiveRecord::Base
  belongs_to :person, :foreign_key => "person_id", :class_name => "User"
  belongs_to :friend, :foreign_key => "friend_id", :class_name => "User"  

# Usage
jack = User.find_by_first_name("Jack")
jill = User.find_by_first_name("Jill")


jack.friends.each do |friend|
  puts friend.first_name
# => Jill

jill.friends.each do |friend|
  puts friend.first_name
# => Jack

this is given a database table schema of

  - id
  - first_name
  - etc...

  - id
  - person_id
  - friend_id

Need Your Help

Polymer 1.0: How to pass an event to a child-node element without using <iron-signals>?

javascript-events polymer polymer-1.0

This Stack Overflow answer suggests using &lt;iron-signals&gt; to broadcast an event down the DOM tree to a custom element.

echoing image files that are being displayed as urls

php html image url

As this page shows it shows the table info I want to see but the image file is just showing the url. In the script I have the uploaded im...