Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete an ActiveRecord object?

How do you delete an ActiveRecord object?

I looked at Active Record Querying and it does not have anything on deleting that I can see.

  1. Delete by id,

  2. Delete the current object like: user.remove,

  3. Can you delete based on a where clause?

like image 754
Blankman Avatar asked Nov 14 '10 13:11

Blankman


People also ask

How do you delete an object in Ruby?

Ruby | Set delete() function The delete() is an inbuilt method in Ruby which deletes the given object from the set and returns the self object. In case the object is not present, it returns self only.

What is an ActiveRecord relation object?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


2 Answers

It's destroy and destroy_all methods, like

user.destroy User.find(15).destroy User.destroy(15) User.where(age: 20).destroy_all User.destroy_all(age: 20) 

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') will allow you to delete records without a primary key

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

like image 135
Marek Sapota Avatar answered Oct 18 '22 22:10

Marek Sapota


There is delete, delete_all, destroy, and destroy_all.

The docs are: older docs and Rails 3.0.0 docs

delete doesn't instantiate the objects, while destroy does. In general, delete is faster than destroy.

like image 43
nonopolarity Avatar answered Oct 18 '22 23:10

nonopolarity