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".

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

First, I create an object :
user =

Then I soft delete it:
# this set deleted_at =

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

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:

Mike Quiney said...

Nice information dear which is pretty useful for me.

Software Development Company Malaysia