Is it possible to look outside of oneself in self.posts.find?

Expanding on recent_posts_on_self below, I want to add the all_recent_posts_on_self method , but I'm not sure if this is possible with the self.posts.find syntax . On the other hand, all_recent_posts_on_class seems simple.

class User < ActiveRecord::Base
  has_many :posts, :class_name => "Post" , :foreign_key => "author_id"
  has_many :comments, :class_name => "Comment", :foreign_key => "author_id"

  def recent_posts_on_class
    Post.find(  :all, :conditions => ['author_id = ?', self.id],
                :order => 'created_at asc', :limit => 5)
  end

  def recent_posts_on_self
    self.posts.find(:all, :order => 'created_at ASC', :limit => 5)
  end
end

      

In the example above, I have two ways to find the latest blog posts related to a user. I can call Post.find and pass its author_id, or I can call self.posts.find and I don't need to pass in the author's id. I guess this is because in the latter case, self.posts was already constrained based on the primary key of the custom object and the has_many: messages associated with that user. This is an advantage in this case, because I don't have to worry about passing author_id as an argument. But if I didn't need to restrict the request to the author, could all_recent_posts_on_self be created to do this?

I mean the equivalent of this method (which omits the conditions :):

  def all_recent_posts_on_class
    Post.find(:all, :order => 'created_at asc', :limit => 5)
  end

      

But using self.posts.find instead of Post.find :

  def all_recent_posts_on_self
    self.posts.find(...)
  end

      

also:

Even though you can use self.posts.find to do this, is it better to use Post.find?

+1


a source to share


2 answers


This is not exactly what you asked, but I find it helpful to know and follow common patterns, avoiding complex or confusing implementations.

The "Rails way" for this is using named areas:

class Post < ActiveRecord::Base
  belongs_to :user
  named_scope :recent, :order => 'created_at desc', :limit => 5
end

class User < ActiveRecord::Base
  has_many :posts
end

      



It doesn't get any more declarative and readable than this:

user.posts.recent # 5 most recent posts by the user
Post.recent # 5 most recent posts globally

      

+4


a source


I'm not sure why you would want to use self.posts.find (..) to search for posts from other authors. This idiom is specifically designed to find a subset of objects associated with a particular instance.



Post.find () is what you should use when you don't want to restrict a specific user model. After all, the posts () method on the User object was just a convenience, which is effectively the same as a (cached) call to Post.find (: all ,: conditions => ['author_id', self.id]).

+1


a source







All Articles