Today I Learned Anonymous Collection Proxies
Landon Schropp •
Today I learned you can pass a block to relationships like has_many, which lets you extend the collection proxy anonymously with new methods.
class Account < ActiveRecord::Base
has_many :people do
def find_or_create_by_name(name)
first_name, last_name = name.split(" ")
find_or_create_by(first_name:, last_name:)
end
end
end
person = Account
.first
.people
.find_or_create_by_name("Landon Schropp")
person.first_name # => "Landon"
person.last_name # => "Schropp"
This is not documented in the Active Record Associations guide, but it is in the ActiveRecord::Assocations::ClassMethods documentation.