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
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).
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).
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.
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.
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
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.
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