26

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?

releod
  • 513
  • 5
  • 12
  • 2
    Why don't you think around it and create a `scope :active, where("deleted_at IS NULL")` and called it when required? – Yannis Oct 18 '10 at 20:41
  • 1
    That's what I would do as well. If you find yourself having to "undo" your default, then it's not really a good default. – Robert Speicher Oct 19 '10 at 00:19
  • 3
    I do not agree on that. I think it is good practice to hide by default and explicitly override that default when needed. This is somehow related to Rails' XSS counter-measures. You had to html_escape every user generated content output in Rails 2. Nowadays, everything is escaped by default and you have to override it manually even if you have much non-user-generated content. It is about security. Information safety in this case. You could get sued for having an unlawful comment on your page because you forgot the named_scope. Or clients freak out to see unpublished content on some page. – crispy Jan 21 '11 at 13:14
  • Related: http://stackoverflow.com/questions/13335726/eager-loading-of-deleted-records-with-paranoias-default-scope – Thilo Aug 05 '14 at 06:03

6 Answers6

17

For some strange reasons,

Comment.unscoped { Post.last.comments }

includes the default_scope of Comment,

however,

Comment.unscoped { Post.last.comments.to_a }
Comment.unscoped { Post.last.comments.order }

do not include the default_scope of Comment.

I experienced this in a rails console session with Rails 3.2.3.

Vikrant Chaudhary
  • 11,089
  • 10
  • 53
  • 68
  • I'm experiencing your issue, in my case `Post.last.comments.order` works, while `Post.last.comments.to_a` is broken. Have you found any clue on this? I'll try to upgrade my app to the latest Rails to see if this is fixed. – Fabio Jul 11 '12 at 14:04
  • 1
    This happens also in 3.2.6, probably a bug. – Fabio Jul 11 '12 at 14:20
  • 1
    Still exists in `rails 4.1.1`, `order(:id)` helps to exclude the default_order. – freemanoid May 27 '14 at 10:10
  • 1
    See [this issue](https://github.com/rails/rails/issues/5591) for more info on the problem. – Alexander Popov Nov 27 '14 at 16:47
10

with_exlusive_scope is deprecated as of Rails 3. See this commit.

Before (Rails 2):

Comment.with_exclusive_scope { Post.find(post_id).comments }

After (Rails 3):

Comment.unscoped { Post.find(post_id).comments }
crispy
  • 5,737
  • 4
  • 33
  • 45
8

Rails 4.1.1

Comment.unscope(where: :deleted_at) { Post.first.comments }

Or

Comment.unscoped { Post.first.comments.scope }

Note that I added .scope, it seems like this block should return kind of ActiveRecord_AssociationRelation (what .scope does) not ActiveRecord_Associations_CollectionProxy (without a .scope)

freemanoid
  • 14,592
  • 6
  • 54
  • 77
6

This is indeed a very frustrating problem which violates the principle of least surprise.

For now, you can just write:

Comment.unscoped.where(post_id: Post.first)

This is the most elegant/simple solution IMO.

Or:

Post.first.comments.scoped.tap { |rel| rel.default_scoped = false }

The advantage of the latter:

class Comment < ActiveRecord::Base
  # ...

  def self.with_deleted
    scoped.tap { |rel| rel.default_scoped = false }
  end
end

Then you can make fun things:

Post.first.comments.with_deleted.order('created_at DESC')

Since Rails 4, Model.all returns an ActiveRecord::Relation , rather than an array of records. So you can (and should) use all instead of scoped:

Post.first.comments.all.tap { |rel| rel.default_scoped = false }
Damien
  • 26,933
  • 7
  • 39
  • 40
1

How about this?

# Use this scope by default
scope :active, -> { where(deleted_at: nil) }

# Use this whenever you want to include all comments regardless of their `deleted_at` value
scope :with_soft_deleted, -> { unscope(where: :deleted_at)

default_scope, -> { active }

post.comments would fire this query:

SELECT "comments".* FROM "comments" WHERE "comments"."deleted_at" IS NULL AND "comments"."post_id" = $1;

post.comments.with_soft_deleted would send this:

SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = $1;
Raam
  • 63
  • 1
  • 8
0
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
  • 19,358
  • 4
  • 30
  • 33
  • 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 Oct 19 '10 at 15:17
  • 1
    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 Oct 19 '10 at 17:40
  • 2
    Wow! this is preatty broken in rails! Like this, the default_scope is unusable. There should be post.unscoped_comments and comment.unscoped_post methods generated... – iwiznia Aug 26 '11 at 18:59
  • I agree. That would be nice to have post.unscoped_comments. But at least you can always do Comment.unscoped { post.comments } to disable the default scope temporarily (for everything inside of the unscoped{} block)... – Tyler Rick Sep 12 '11 at 15:25