Why is using the rails default_scope often recommend against?

后端 未结 5 2327
执笔经年
执笔经年 2020-11-28 03:59

Everywhere on the internet people mention that using the rails default_scope is a bad idea, and the top hits for default_scope on stackoverflow are

5条回答
  •  情书的邮戳
    2020-11-28 04:20

    Another reason to not use default_scope is when you're deleting an instance of a model that has a 1 to many relation with the default_scope model

    Consider for example:

        class User < ActiveRecord::Base
          has_many :posts, dependent: :destroy
        end 
    
        class Post < ActiveRecord::Base
          default_scope { where(published: true) }
          belongs_to :user
        end
    

    Calling user.destroy will delete all the posts that are published, but it won't delete posts that are unpublished. Hence the database will throw a foreign key violation because it contains records that reference the user you want to remove.

提交回复
热议问题