Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I do reflexive self-join relationships in ActiveRecord?
    primarykey
    data
    text
    <p>I'm trying to implement a social networking style friendship model and I didnt have much much luck trying to figure out the plugins available out there. I think I'll learn Rails better if I do it myself. So here's what I have :</p> <pre><code>class User &lt; ActiveRecord::Base has_many :invitee_friendships , :foreign_key =&gt; :friend_id, :class_name =&gt; 'Friendship' has_many :inviter_friends, :through =&gt; :invitee_friendships has_many :inviter_friendships , :foreign_key =&gt; :user_id, :class_name =&gt; 'Friendship' has_many :invited_friends, :through =&gt; :inviter_friendships end class Friendship &lt; ActiveRecord::Base belongs_to :user //I think something needs to come here, i dont know what end </code></pre> <p>In <code>irb</code> when I try this:</p> <pre><code>friend1 = Friend.create(:name =&gt; 'Jack') friend2 = Friend.create(:name =&gt; 'John') bff = Friendship.create(:user_id =&gt;1, :friend_id =&gt; 2) f1.invited_friends </code></pre> <p>I get an error:</p> <pre><code>ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :invited_friend or :invited_friends in model Friendship. Try 'has_many :invited_friends, :through =&gt; :invited_friendships, :source =&gt; &lt;name&gt;'. Is it one of :user? </code></pre> <p><strong>Expanation of friendship system:</strong></p> <ul> <li>A user can invite other users to become friends.</li> <li>Users who you invited to become friends are represented by <code>invited_friends</code>.</li> <li>Users who invited you to become friends are represented by <code>inviter_friends</code>.</li> <li>Your total friend list is represented by <code>invited_friends</code> + <code>inviter_friends</code>.</li> </ul> <p><strong>Schema</strong></p> <pre><code>table Friendship t.integer :user_id t.integer :friend_id t.boolean :invite_accepted t.timestamps table User t.string :name t.string :description </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload