Kevin Jiang

tilInteresting Rails Conventions

As a noob in programming in Ruby on Rails, I feel like there’s a lot to learn. Unfortunately Intellisense doesn’t work great leading to harder discoverability. Convention over configuration is great, but only if you already know that convention. Here’s some miscellaneous things that I found interesting while reading the Ruby on Rails guides (for v7.1.2).

Disclaimer: I’m still very new to this, so if anything here is wrong please let me know!

Notes:

Full text:

class Author < ApplicationRecord
  has_many :books, dependent: :destroy
end

class Book < ApplicationRecord
  belongs_to :author
end

namespace :active_storage do
  desc "Purges unattached Active Storage blobs. Run regularly."
  task purge_unattached: :environment do
    ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)
  end
end

The query generated by ActiveStorage::Blob.unattached can be slow and potentially disruptive on applications with larger databases.

  1. use \A and \z to match the start and end of the string, ^ and $ match the start/end of a line. Due to frequent misuse of ^ and $, you need to pass the multiline: true option in case you use any of these two anchors in the provided regular expression. In most cases, you should be using \A and \z.