ruby on rails - Soft delete with associations -
i have 3 models:
user:
class user < activerecord::base has_many :posts, :dependent => :destroy scope :active, -> { where(deleted: false) } end
post:
class post < activerecord::base belongs_to :user has_many :comments, :dependent => :destroy scope :active, -> { where(deleted: false) } end
comment:
class comment < activerecord::base belongs_to :post scope :active, -> { where(deleted: false) } end
now, doing soft delete user
, have column named deleted
in 3 tables(user, post, comment
)
user destroy method:
def destroy @user = user.find(params[:id]) if @user.update_attributes(deleted: true) @user.posts.each |post| post.comments.update_all(deleted: true) end @user.posts.update_all(deleted: true) end end
the above implementation takes more time when no. of posts , comments high , creates n+1 query problem..
same above have implemented destroy
method post
, don't know how efficiently..
i don't want use kind of gem.
please tell me better way soft deletion these kind of associations..
do need delete posts? scope them out instead including user model when retrieve them. marking descendants deleted isn't necessary when can inferred parent.
user:
class user < activerecord::base has_many :posts, :dependent => :destroy scope :active, -> { where(deleted: false) } end
post:
class post < activerecord::base belongs_to :user has_many :comments, :dependent => :destroy scope :active, -> { joins(:user).merge(user.active) } end
Comments
Post a Comment