Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You basically have it right, except for a few minor errors:</p> <ul> <li><p><code>attr_accessible :relations_id</code> is redundant. Remove it from your <code>Relationship</code> model.</p></li> <li><p>Both <code>Relationship</code> and <code>User</code> models call <code>has_many</code> to associate with each other. <code>Relationship</code> should call <code>belongs_to</code> because it contains the foreign key.</p></li> <li><p>In your <code>User</code> model, set <code>:foreign_key =&gt; "follower_id"</code>.</p></li> </ul> <hr> <p>Here is how I would do it.</p> <p>Have a <code>Follow</code> middle class with polymorphic association on the <code>followable</code> content side and has_many on the <code>follower</code> user side (user has many follows).</p> <p>First, create a <code>follows</code> table:</p> <pre><code>class CreateFollows &lt; ActiveRecord::Migration def change create_table :follows do |t| t.integer :follower_id t.references :followable, :polymorphic =&gt; true t.timestamps end end end </code></pre> <p>Replace <code>Relationship</code> model with a <code>Follow</code> model:</p> <pre><code>class Follow &lt; ActiveRecord::Base belongs_to :followable, :polymorphic =&gt; true belongs_to :followers, :class_name =&gt; "User" end </code></pre> <p>Include in <code>User</code> model:</p> <pre><code>has_many :follows, :foreign_key =&gt; :follower_id </code></pre> <p>Include in your three followable classes: </p> <pre><code>has_many :follows, :as =&gt; :followable </code></pre> <p>You can now do this: </p> <pre><code>TheContent.follows # =&gt; [Follow,...] # Useful for counting "N followers" User.follows # =&gt; [Follow,...] Follow.follower # =&gt; User Follow.followable # =&gt; TheContent </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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