Delete from database with specific details in ruby
From the comments, I learned that you are running a very old version of Ruby on Rails – probably more than 10 years old. With Rails 3.0 the finder methods change completely and therefore all current documentation for Rails will not be helpful anymore. Especially the where
method did not exist before Rails 3.0
In such an old version the following should work:
YourModel.destroy_all("id in (?)", @recipient.split(','))
Here you will find the docs of older Rails versions.
The condition is basically just one SQL fragment. When you want to add more conditions then you need to write all conditions in one line like this:
YourModel.destroy_all(
"id IN (?) AND thread = ?", @recipient.split(','), @dis_PI.m_id
)
Deleting all records in a database table
If you are looking for a way to it without SQL you should be able to use delete_all.
Post.delete_all
or with a criteria
Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
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.
Deleting a record from database
@variable.destroy
will call all callbacks (before_destroy etc.) as well as ensure associations are respected. @variable.delete
just calls the raw database query to delete the object. You're generally much safer off using destroy
even if it's more expensive.
Only delete from memory not from database
Beware if you are using has_many relationship the answer by JP will not work.
Extending the example:
class City < ActiveRecord::Base
has_many :shops
end
city = City.find(:name => "Portland")
then
city.shops.delete(city.shops[0])
Will delete from the DB!
Also
theshops = city.shops
theshops.delete(ss[0])
Will delete from the DB
One way to detach from the DB is to use compact or another array function like so:
theshops = city.shops.compact
theshops.delete(ss[0])
Will not delete from the DB
Also, in all cases delete_if Will not delete from the db:
city.shops.delete_if {|s| s.id == city.shops[0]}
Cheers!
Don't forget: If you are in doubt about these sort of things script/console is your friend!
how to automatically delete a record from the database in rails
There are different ways on how to handle this task. Check 2 options below.
Option 1 - whenever gem
You would setup a task using whenever which runs for example every 30 days.
1- Generate task as following:
rails g task posts delete_30_days_old
2- Create a ruby file in your application
# lib/tasks/delete_old_records.rb
namespace :posts do
desc "Delete records older than 30 days"
task delete_30_days_old: :environment do
Post.where(['created_at < ?', 30.days.ago]).destroy_all
end
end
Option 2 - sidekick and Sidetiq gems
# in app/workers/clean_posts.rb
class CleanPosts
include Sidekiq::Worker
include Sidetiq::Schedulable
recurrence { monthly }
def perform
Post.recent.destroy_all
end
end
and
# /models/post.rb
class Post < ApplicationRecord
scope :recent, -> { where('created_at >= :thirty_days_ago', thiryty_days_ago: Time.now - 30.days) }
end
Since Ruby is about beauty, move the where clause to your model, where can reuse it.
These options will remove old posts from your DB and they will no longer be accessible by your application.
How do you delete an ActiveRecord object?
It's destroy
and destroy_all
methods, like
user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)
Alternatively you can use delete
and delete_all
which won't enforce :before_destroy
and :after_destroy
callbacks or any dependent association options.
User.delete_all(condition: 'value')
will allow you to delete records
without a primary key
Note: from @hammady's comment, user.destroy
won't work if User model has no primary key.
Note 2: From @pavel-chuchuva's comment, destroy_all
with conditions and delete_all
with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html
Rails - Delete all Records that Meet a Condition
I think it is better to use destroy instead of delete
because destroy will delete current object record from db and also its
associated children record from db (https://stackoverflow.com/a/22757656/5452072)
Also delete will skip callbacks, but destroy doesn't.
Manager.where(:manager_level => 5).destroy_all
Related Topics
Error Occurs When Trying to Install Homebrew on a MAC for Ruby on Rails
Proc Throws Error When Used with Do End
Ruby Was-Sdk V2:Seahorse::Client::Networkingerror Exception: Ssl_Connect
Ruby: Unexpected End-Of-Input, Expecting Keyword_End for If Statement
Invalid Route Name, Already in Use: 'Admin_Root' (Argumenterror) - Failed Activeadmin Install
Newbie: Text Replacement in My Case
How to Handle Partials in an SCSS Project
How to Find the Average of 3 Date in Ruby on Rails or Ruby
Count, Size, Length...Too Many Choices in Ruby
Sorting an Array of Objects in Ruby by Object Attribute
Why Does the Script Affect Everything on My Rails 3 App Even When Cased in This Code
Using Devise for More Than One Models in Rails App
When Joining Table, Rails Anyway Makes Additional Request When Accessing Fields from Joined Table
Pulling a Value from One CSV Based on a Value in Another
How Does Rails Know My Timezone