Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use Record.all.destroy in Rails?

I'm currently beginning to learn Ruby and the Ruby on Rails framework. I've found that in the table records, I can find a record with an id of 5 and delete it by using the following code:

Record.find(5).destroy

This makes sense- I chain methods to find the record and destroy it. However, if I want to destroy all the records in the table, the logical command would be the following, as the all selector selects all the records in the table:

Record.all.destroy

And this returns a NoMethodError! I am aware that I can use Record.destroy_all or Record.delete_all to accomplish this task, however, I'd like to know why I can't just use the most logical choice instead of having to look up things like delete_all. I am new to this framework, so it's entirely possible that I'm missing something fundamental here.

Thanks for any answers in advance.

like image 838
element119 Avatar asked May 30 '11 16:05

element119


People also ask

How do you destroy a record in rails?

By using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.

What is the difference between delete and destroy in rails?

Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.


1 Answers

It was a design decision. DataMapper took your approach. Being forced to write destroy_all explicitly can be tedious but will also prevent you from doing something you really don't want (i.e. delete everything in a table, like x = User; ...; x.destroy).

like image 127
Marcel Jackwerth Avatar answered Oct 22 '22 09:10

Marcel Jackwerth