views:

25

answers:

1

Suppose I have a Post model, and a Comment model. Using a common pattern, Post has_many Comments.

If Comment has a default_scope set:

default_scope where("deleted_at IS NULL")

How do I easily retrieve ALL comments on a post, regardless of scope? This produces invalid results:

Post.first.comments.unscoped

Which generates the following queries:

SELECT * FROM posts LIMIT 1;
SELECT * FROM comments;

Instead of:

SELECT * FROM posts LIMIT 1;
SELECT * FROM comments WHERE post_id = 1;

Running:

Post.first.comments

Produces:

SELECT * FROM posts LIMIT 1;
SELECT * FROM comments WHERE deleted_at IS NULL AND post_id = 1;

I understand the basic principle of unscoped removing all existing scopes, but shouldn't it be aware and to keep the association scope?

What is the best way to pull ALL comments?

A: 
class Comment
  def post_comments(post_id)
    with_exclusive_scope { find(all, :conditions => {:post_id => post_id}) }
  end
end

Comment.post_comments(Post.first.id)
Faisal
To me that feels a bit hackish though. Posts/Comments, is only an example, you wouldn't want to repeat this across many different models would you?I realize I didn't mention that originally too.
releod
This will get really ugly really quickly. If this too hackish to your taste (it really is hackish), try to re-evaluate using default_scope in the first place.
Faisal