Friday, February 15, 2013

Rails default_scope delete

I have a model called User with a default_scope where('deleted_at is null'), because I'm using some kind of "soft delete".

Problem:
I want to delete an object who has been soft deleted.

First, I create an object :
user = User.new

Then I soft delete it:
user.soft_delete
# this set deleted_at = Time.now

Then I want to delete it:
user.delete
# nothing happen !
# the query looks like this: delete from users where id = 1 and deleted_at is null

Solution:
I can think about 2 solutions:

1) Is to execute sql code directly:

ActiveRecord::Base.connection.execute("delete from ...");

2) Use "unscoped"
User.unscoped.where(:id => 1).delete_all

And that's it!

If you know a better solution, please let me know

1 comment:

Unknown said...

Nice information dear which is pretty useful for me.

Software Development Company Malaysia