How to preview a delete
You know the drill: some invalid data pops up in the production database and you have to get rid of it. You fire up your Rails console on the production server and type in the query:
Foo.where(bar: 'baz').all
You review the returned data and it's what you need to remove. Then you type:
Foo.where(bar: 'baz').destroy_all
And your heart stops for a second. You just want to see the query before it runs.
Is there any way to do that in Rails? I'm looking for a method similar to
Foo.where(bar: 'baz').to_sql
but the one that will return the DELETE query.
Just off the top of my head, you could run the console in sandbox mode and run the delete query to see the sql. The changes would just be rolled back on exit.
The problem is that destroy_all does not run a single SQL query. It iterates through a hash of objects, instantiates them, runs their callbacks, and then calls that object's destroy method. Rails has no built in way of producing an array of these queries.
Cdesroisiers is right that you can test the query in sandbox mode, but the real problem is that you're second-guessing your decision to run delete_all, even though you've verified whatever data is being targeted.
Consider using an ActiveRecord versioning gem like PaperTrail if you're not willing to trust ActiveRecord to properly delete objects.
the destroy_all method is the same as doing:
Foo.where(bar: 'baz').each { |object| object.destroy }
So the sql becomes
DELETE FROM foo WHERE foo.id = your_objects_id_attribute
From docs:
def destroy_all(conditions = nil)
find(:all, :conditions => conditions).each { |object| object.destroy }
end
链接地址: http://www.djcxy.com/p/60340.html
上一篇: 使用按钮的自定义视图实现OnGestureListener
下一篇: 如何预览删除