10

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.

4 Answers4

23

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
Benjamin Bouchet
  • 12,971
  • 2
  • 41
  • 73
  • i want to destroy `user.agents` and I tried `user.agents.destroy,but it gives me error. –  Jul 19 '13 at 11:30
  • 1
    it's either `user.destroy` either `user.agents.destroy_all`. First one act on a single record, second one act on a collection – Benjamin Bouchet Jul 26 '13 at 01:12
6

You are looking for a .destroy_all method. It destroys all records of a given collection. So user.agents.destroy_all, would return an empty array for user.agents.

You could not have used .delete_all because it is a class method and it deletes records that match a given condition. Like this, Agent.delete_all(condition). If used without a condition it deletes all records from a matched table.

Keep in mind that .destroy methods are instance methods. They instantiate an object and perform callbacks before erasing it. .delete methods are class methods and they directly erase an object.

dariodaic
  • 71
  • 4
1

This works for me

user.agents.find_each(&:destroy)
Geebrok
  • 21
  • 2
-1
ActiveRecord::StaleObjectError 

Is for Optimistic locking, remove any locks you have on it before trying to delete again. Check if anyone else is using the system or submit any forms you have open.

DickieBoy
  • 4,886
  • 1
  • 28
  • 47