--- title: Interesting Rails Conventions permalink: interesting-rails-conventions date: 2023-12-01T12:06:08-05:00 tags: rails --- 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: - In regex, use `\A` and `\z` to indicate the start and end of the string. [^a] - `has_many :books, dependent: :destroy` [^b] - Use `has_and_belongs_to_many` to build an implicit join table easily, otherwise `has_many :through` - Symbol vs String: Use Symbol when the identity of it matters, use String when contents matter - `-> { method }` or `->(args) { method(args)}` is a lambda - Metaprogramming makes things confusing. As a beginner, try not to touch it if possible (and to keep code readable). - ActiveJob is really cool - You can use `<%= method %>` erb-style interpolation in YAML files, somehow. I should figure out how. - An ActiveStorage "file" is called an attachment - You should periodically purge unattached uploads [^c] ## Full text: [^a]: 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`. [^b]: ```rb class Author < ApplicationRecord has_many :books, dependent: :destroy end class Book < ApplicationRecord belongs_to :author end ``` [^c]: ```rb 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.