I just released version 1.0.0 of my gem active_record_compose. 🎉
hamajyotan/active_record_compose (GitHub)
As mentioned in my previous post, this gem has been continuously improved.
Today, I'm excited to announce version 1.0.0!
If you’re curious, here’s my previous post:
Smart way to update multiple models simultaneously in Rails
ActiveRecord Compose is a Ruby gem that implements the form object pattern, allowing you to combine multiple ActiveRecord models into a single, unified business interface.
It goes beyond simple form objects: for example, handling user registration that spans multiple tables. With this approach, complex business operations become easier to write, validate, and maintain. It is built on top of ActiveModel::Model, leveraging the existing Rails infrastructure.
Example:
class Foo < ApplicationRecord
validates :name, presence: true
end
class Bar < ApplicationRecord
validates :age, presence: true
end
class Baz < ActiveRecordCompose::Model
def initialize(attributes)
@foo = Foo.new
@bar = Bar.new
models << foo << bar
super(attributes)
end
delegate_attribute :name, to: :foo
delegate_attribute :age, to: :bar
private attr_reader :foo, :bar
end
baz = Baz.new(name: "qux", age: nil)
baz.attributes #=> {"name" => "qux", "age" => nil}
baz.save #=> false # validation from Bar propagates to Baz
baz.errors.to_a #=> ["Age can't be blank"]
baz.age = 36
baz.save #=> true
[Foo.count, Bar.count] #=> [1, 1]
Sample Application
https://github.com/hamajyotan/active_record_compose-example
This is a simple micro-blogging application. The app/models/
directory serves as an example of how to use this gem.
Would love feedback or real-world use cases if you try it out!
Top comments (0)