Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails , when using destroy_all, is there a way to return number of records, if any deleted?

right now I have:

PollVote.destroy_all(:user_id => record.user_id, :poll_id => record.poll_id)

Is there a way I can get back the number, deleted? 0 or more?

deleted_count = PollVote.destroy_all(:user_id => record.user_id, :poll_id => record.poll_id)

deleted_count being either 0 or higher?

Thanks

like image 782
AnApprentice Avatar asked Jun 26 '11 22:06

AnApprentice


People also ask

What does Destroy_all return?

Method: ActiveRecord::Relation#destroy_all Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can't be persisted).

Does Destroy_all trigger callbacks?

destroy_all(conditions = nil) Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object's callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods).

What is the difference between delete and destroy in Rails?

Rails Delete operation using delete method Unlike the destroy method, with delete, you can remove a record directly from the database. Any dependencies to other records in the model are not taken into account. The method delete only deletes that one row in the database and nothing else.

What is dependent destroy in Rails?

Dependent is an option of Rails collection association declaration to cascade the delete action. The :destroy is to cause the associated object to also be destroyed when its owner is destroyed.


2 Answers

Per the documentation, destroy_all returns a collection of the objects destroyed. Knowing this, all you need to do is get that collection's length:

destroyed = PollVote.destroy_all(:user_id => record.user_id, :poll_id => record.poll_id)

destroyed_count = destroyed.length # => The number of records destroyed
like image 131
Jordan Running Avatar answered Nov 15 '22 11:11

Jordan Running


If you use delete_all, it will skip all the destroy callbacks for the records that you're deleting (helpful for when you don't want these to run) and it will return the number of records that have been deleted.

like image 20
Ryan Bigg Avatar answered Nov 15 '22 09:11

Ryan Bigg