Delete everything in rails console

I have an association for the user as user has_many agents and agent belongs_to user . in the rails console , I'm trying to use different users to test a specific scenario, and I want the user to have no agents, so I want to remove user.agents . I tried user.agents.map(&:destroy) , but it gives an error like ActiveRecord::StaleObjectError: Attempted to delete a stale object .i even tried user.agents.delete_all , but it doesn't work either. I can remove user agents with a single command in the rails console.

+8
ruby ruby-on-rails ruby-on-rails-3 rails-console
source share
4 answers

It is better to use destroy because it goes through all the magic of Rails (callbacks, etc.)

 user.destroy #For a single record user.agents.destroy_all #For a collection 
+18
source share

You are looking for the .destroy_all method. It destroys all entries in this collection. So user.agents.destroy_all will return an empty array for user.agents .

You could not use .delete_all because it is a class method and it deletes records matching this condition. For example, Agent.delete_all(condition) . If used without a condition, it deletes all records from the associated table.

Keep in mind that .destroy methods are instance methods. They instantiate the object and call back before erasing it. .delete methods are class methods and they directly erase the object.

+5
source share

It works for me

 user.agents.find_each(&:destroy) 
+1
source share
 ActiveRecord::StaleObjectError 

For Optimistic Lock, remove all locks that you have before trying to remove them again. Make sure anyone else is using the system or submitting open forms.

0
source share

All Articles