default_scope and associations
Asked Answered
C

6

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?

Conjuration answered 18/10, 2010 at 20:30 Comment(4)
Why don't you think around it and create a scope :active, where("deleted_at IS NULL") and called it when required?Tagmemics
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.Septennial
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.Cohere
Related: #13336226Bedpan
B
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.

Beastings answered 9/5, 2012 at 9:40 Comment(4)
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.Laryssa
This happens also in 3.2.6, probably a bug.Laryssa
Still exists in rails 4.1.1, order(:id) helps to exclude the default_order.Matti
See this issue for more info on the problem.Pantaloons
C
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 }
Cohere answered 21/1, 2011 at 13:22 Comment(0)
M
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)

Matti answered 27/5, 2014 at 10:15 Comment(0)
N
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 }
Noblesse answered 17/5, 2013 at 18:21 Comment(0)
M
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;
Maurreen answered 3/2, 2020 at 8:27 Comment(0)
L
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)
Linctus answered 19/10, 2010 at 6:6 Comment(4)
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.Conjuration
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.Linctus
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...Dratted
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)...Slipshod

© 2022 - 2024 — McMap. All rights reserved.