- Published
- Author
- Mohammad hussainSystem Analyst
Rails has a built-in way to reduce repetition in associations—
When multiple
Using with_options, you can group them under one block:
This makes the intent clearer—all these associations share the same rule.
It's easier to read, less error-prone, and keeps your model DRY ✨
#Rails
with_options.When multiple
has_many relationships share the same option (like dependent: :destroy), repeating it clutters your model:Code
class Account < ApplicationRecord
has_many :customers, dependent: :destroy
has_many :products, dependent: :destroy
has_many :invoices, dependent: :destroy
has_many :expenses, dependent: :destroy
endUsing with_options, you can group them under one block:
Code
class Account < ApplicationRecord
with_options dependent: :destroy do
has_many :customers
has_many :products
has_many :invoices
has_many :expenses
end
endThis makes the intent clearer—all these associations share the same rule.
It's easier to read, less error-prone, and keeps your model DRY ✨
#Rails