Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails: has_many referential --which model objects does it own?
    primarykey
    data
    text
    <p>I am new to Rails and finished Michael Hartl's "Ruby on Rails 3 Tutorial". Although the book teaches me a lot, I find this puzzle I don't understand. </p> <p>To preview the puzzle, that is, I don't understand, inside User model, </p> <pre><code>has_many :following, :through=&gt;:relationship, :source=&gt;:followed </code></pre> <p>how this piece of code link "user.following" to an array of User instances. </p> <p>And below is the whole puzzle.</p> <p>First of all, I have the <strong>Relationship</strong> model, which records <strong>followed_id</strong> and <strong>follower_id</strong> infos. Inside <strong>Relationship</strong> model, the association is simple as </p> <pre><code>class Relationship &lt; ActiveRecord::Base attr_accessible :followed_id belongs_to :follower, :class_name =&gt; "User" belongs_to :followed, :class_name =&gt; "User" end </code></pre> <p>Then, inside the User model, a user will assume the role of <strong>follower</strong>, and collect all its <strong>following</strong> rows in relationships table through <strong>relationships</strong> association. </p> <pre><code>class User &lt; ActiveRecord::Base . . . has_many :relationships, :foreign_key =&gt; "follower_id", :dependent =&gt; :destroy . </code></pre> <p>Until now, I got it.</p> <p>But confusion came at the next line, where through <strong>user.following</strong> it can assemble all that user's following(User instances). Like so,</p> <pre><code>has_many :following, :through=&gt;:relationships, :source=&gt;:followed </code></pre> <p>I understand that <strong>:source=>:followed</strong> will overwrite the default, and let find all <strong>followed_ids</strong> associated with that user. </p> <p><strong>But</strong>, how can Rails recognize <strong>followed_id</strong> to link to <strong>User</strong> object? The label name doesn't match <strong>users</strong>, nor is there <strong>:class_name</strong> specified. I just don't get how Rails do this underlying work, or I missed out some hints. </p> <p>Thank you! :)</p>
    singulars
    1. This table or related slice is empty.
    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. 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