Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a record from console -- Ruby on Rails

I want to delete a record from the console.

I logged through script/console and

User.find(1).delete
$<User id: 1, ..............>
User.find(1)
ActiveRecord::RecordNotFound: Couldn't find User with ID=1
........
........
........

Everything looks fine till here.

But when I exit the console and return back to console by script/console command, I am able again to see the record with id = 1.

The database is not local and I'm connecting through database.yml by giving an ip.

when I try to do the same on the development local database, everything is fine.

Can someone please explain whats happening and where am I missing!

Thanks

like image 549
kill007 Avatar asked Aug 15 '11 18:08

kill007


People also ask

How do I delete a record in Ruby on 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.

How do I delete a row from a table in Ruby?

To delete a row at any location, call the deleteRows method of the Cells collection. The DeleteRows method takes two parameters: Row index, the index of the row from where the rows will be deleted. Number of rows, total number of rows that need to be deleted.

How do you delete 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.

How delete all data from table in rails?

If you are looking for a way to it without SQL you should be able to use delete_all. See here for more information. The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.


3 Answers

Try

User.find(1).destroy

This should work in the console and otherwise.

like image 67
vandrop Avatar answered Oct 16 '22 08:10

vandrop


On a similar note you can remove all the tuples for a given Object from the rails console as follows:

@object = Object.all

@object.each do |o|
  o.delete
end
like image 38
Adam Hammouda Avatar answered Oct 16 '22 07:10

Adam Hammouda


Easy way to remove Models data from console

rails console

Store user model to an instance variable

user = User.find(1)

delete or destroy the relations by following commands

user.delete

or

user.destroy
like image 2
Dinesh Pallapa Avatar answered Oct 16 '22 08:10

Dinesh Pallapa