Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to look beyond self in self.posts.find?
    primarykey
    data
    text
    <p>Expanding on recent_posts_on_self below, <strong>I want to add an all_recent_posts_on_self method</strong> but I'm not sure if it's possible <strong>using the syntax self.posts.find</strong>. On the other hand, all_recent_posts_on_class seems straightforward.</p> <pre><code>class User &lt; ActiveRecord::Base has_many :posts, :class_name =&gt; "Post" , :foreign_key =&gt; "author_id" has_many :comments, :class_name =&gt; "Comment", :foreign_key =&gt; "author_id" def recent_posts_on_class Post.find( :all, :conditions =&gt; ['author_id = ?', self.id], :order =&gt; 'created_at asc', :limit =&gt; 5) end def recent_posts_on_self self.posts.find(:all, :order =&gt; 'created_at ASC', :limit =&gt; 5) end end </code></pre> <p>In the example above, I have two ways of finding the recent blog posts that are associated with a user. I can call Post.find and pass it the author_id or I can call self.posts.find and I don't need to pass an author id. I assume this is because in the latter case, self.posts has already been limited based on the primary key of the user object and the has_many :posts associated with this user. This is an advantage in this case because I don't need to go to the trouble of passing author_id as an argument. But if I did not need to limit the query by author, would it be possible to create an all_recent_posts_on_self to do this? </p> <p><strong>What I'm talking about is an equivalent of this method</strong> (which omits the :conditions):</p> <pre><code> def all_recent_posts_on_class Post.find(:all, :order =&gt; 'created_at asc', :limit =&gt; 5) end </code></pre> <p><strong>But using self.posts.find instead of Post.find</strong>:</p> <pre><code> def all_recent_posts_on_self self.posts.find(...) end </code></pre> <p>Also:</p> <p><strong>Even if it's possible to use self.posts.find to do this, is it "better" to use Post.find?</strong></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.
    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