Skip to content

Instantly share code, notes, and snippets.

@cybersamx
Last active June 10, 2021 16:34
Show Gist options
  • Save cybersamx/b9dd6a67fa7fcc8598ab to your computer and use it in GitHub Desktop.
Save cybersamx/b9dd6a67fa7fcc8598ab to your computer and use it in GitHub Desktop.
Find/Remove ActiveRecord older than n days
# Get objects older than 3 days.
@models = MyModel.where('created_at < :time', { time: 3.days.ago })
@models = MyModel.where(['created_at < ?', 3.days.ago])
# Get objects within the last 3 days.
@models = MyModel.where('created_at >= :time', { time: 3.days.ago })
@models = MyModel.where(['created_at >= ?', 3.days.ago])
# Multiple conditions.
@models = MyModel.where(['created_at >= ? and name like ?', 3.days.ago, 'Sam%'])
# Destroy objects older than 3 days.
MyModel.destroy_all(['created_at < ?', 3.days.ago])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment