Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, destroy versus delete?

Why does this work:

@poll_votes = PollVote.where(:user_id => self.user_id, :poll_id => self.poll_id).all

@poll_votes.each do |p|
  p.destroy
end

But this does not?

@poll_votes = PollVote.where(:user_id => self.user_id, :poll_id => self.poll_id).destroy
like image 987
AnApprentice Avatar asked Jun 26 '11 03:06

AnApprentice


People also ask

How do you destroy in rails?

Rails delete operation using destroy methodBy 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 soft delete in rails?

Any record where that column has a non- NULL value is considered to be soft-deleted. When a record is deleted via Active Record (the default ORM library packaged with Ruby on Rails), instead of actually deleting the record from the database, populate the deleted_at column with the time of deletion.

How do you destroy an object in Ruby?

You can't explicitly destroy object. Ruby has automatic memory management. Objects no longer referenced from anywhere are automatically collected by the garbage collector built in the interpreter.

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

The where method returns an enumerable collection of activerecord objects meeting the selection criteria. Calling the destroy method on that collection is different than calling the destroy method on a single activerecord object.

like image 151
Fred Avatar answered Oct 11 '22 05:10

Fred


This should work: PollVote.destroy_all(:user_id => self.user_id, :poll_id => self.poll_id)

like image 34
moc Avatar answered Oct 11 '22 03:10

moc