How do I make reflective relationships for self-join in ActiveRecord?

I’m trying to implement a friendship model on social networks, and I didn’t have much luck trying to figure out the plugins available there. I think I'd better learn Rails if I do it myself. So here is what I have:

class User < ActiveRecord::Base has_many :invitee_friendships , :foreign_key => :friend_id, :class_name => 'Friendship' has_many :inviter_friends, :through => :invitee_friendships has_many :inviter_friendships , :foreign_key => :user_id, :class_name => 'Friendship' has_many :invited_friends, :through => :inviter_friendships end class Friendship < ActiveRecord::Base belongs_to :user //I think something needs to come here, i dont know what end 

In irb , when I try this:

 friend1 = Friend.create(:name => 'Jack') friend2 = Friend.create(:name => 'John') bff = Friendship.create(:user_id =>1, :friend_id => 2) f1.invited_friends 

I get an error message:

 ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :invited_friend or :invited_friends in model Friendship. Try 'has_many :invited_friends, :through => :invited_friendships, :source => <name>'. Is it one of :user? 

Friendship system expansion:

  • The user can invite other users to become friends.
  • The people you invited to become friends are invited_friends .
  • Users who invited you to become friends are represented by inviter_friends .
  • Your general friend list is presented by invited_friends + inviter_friends .

Scheme

 table Friendship t.integer :user_id t.integer :friend_id t.boolean :invite_accepted t.timestamps table User t.string :name t.string :description 
+4
source share
1 answer

I am surprised that no one pointed to the recent Ryan Bates screencast on the topic :)

Hope this helps !.

An excerpt from Ryan '... requires associative association in the User model to identify friends / followers

+7
source

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


All Articles