default_scope and associations

前端 未结 6 1581
猫巷女王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:01

    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;
    

提交回复
热议问题