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:
-
In regex, use
\A
and\z
to indicate the start and end of the string. 1 -
has_many :books, dependent: :destroy
2 -
Use
has_and_belongs_to_many
to build an implicit join table easily, otherwisehas_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 3
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.
-
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
. - ↩
- ↩