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.
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.
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With