default_scope and associations

前端 未结 6 1578
猫巷女王i
猫巷女王i 2020-12-06 04:17

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 w         


        
6条回答
  •  天命终不由人
    2020-12-06 05:19

    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 }
    

提交回复
热议问题