Delete all in rails console

user2164011 picture user2164011 · Jul 19, 2013 · Viewed 19.1k times · Source

i have an association for a user as user has_many agents and agent belongs_to user. in rails console,i am trying to use different users to test a particular scenario and i want a user with no agents,hence i want to delete the user.agents. i tried user.agents.map(&:destroy),but it gives error as ActiveRecord::StaleObjectError: Attempted to delete a stale object.i even tried user.agents.delete_all but it too does not work.can i delete the users agents with a single command in rails console.

Answer

Benj picture Benj · Jul 19, 2013

You better use destroy because it goes through all the Rails magic (callbacks and such)

user.destroy #For a single record
user.agents.destroy_all #For a collection