Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to setup and work with RoR Complex Joins?
    primarykey
    data
    text
    <p>This code is taken from a previous question, but my question directly relates to it, so I've copied it here:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :group_memberships has_many :groups, :through =&gt; :group_memberships end class GroupMembership &lt; ActiveRecord::Base belongs_to :user belongs_to :role belongs_to :group end class Role &lt; ActiveRecord::Base has_many :group_memberships end class Group &lt; ActiveRecord::Base has_many :group_memberships has_many :users, :through &gt; :group_memberships end </code></pre> <p><strong>New Question Below</strong></p> <p>How you take the above code one step further and add and work with friends?</p> <pre><code>class User &lt; ActiveRecord::Base has_many :group_memberships has_many :groups, :through =&gt; :group_memberships has_many :friends # what comes here? has_many :actions end </code></pre> <p>In the code above I also added actions. Let's say that the system kept track of each user's actions on the site. How would you code this so that each action was unique and sorted with the most recent at the top for all the user's friends?</p> <pre><code>&lt;% for action in @user.friends.actions %&gt; &lt;%= action.whatever %&gt; &lt;% end %&gt; </code></pre> <p>The code above may not be valid, you could do something like what I have below, but then the actions wouldn't be sorted.</p> <pre><code>&lt;% for friend in @user.friends %&gt; &lt;% for action in friend.actions %&gt; &lt;%= action.whatever %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p><strong>UPDATE</strong></p> <p>I guess the real issue here is how to define friends? Do I create a new model or join table that links users to other users? Ideally, I'd like to define friends through the common group memberships of other users, but I'm not sure how to go about defining that.</p> <pre><code>has_many :friends, :through =&gt; :group_memberships, :source =&gt; :user </code></pre> <p>But that doesn't work. Any ideas or best practice suggestions?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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