Castkit::ActiveRecord is a companion gem to Castkit that bridges your Castkit::DataObject classes with ActiveRecord models. It enables conversion to/from models, assignment, and safe update flows for nested objects.
bundle add castkit-activerecordInclude the module in your Castkit::DataObject class and associate it with a model:
class UserDto < Castkit::DataObject
include Castkit::ActiveRecord
model User
string :name
has_many :posts, of: PostDto
enduser_dto = UserDto.from_model(User.find(1))user_model = user_dto.to_modeluser.update_from_dataobject(user_dto, mode: :merge)Use update_from_dataobject! if you want to raise on failure. Pass ignore: [:field] to skip certain fields.
Nested dataobject and has_many/has_one relationships are supported:
class PostDto < Castkit::DataObject
include Castkit::ActiveRecord
model Post
string :title
dataobject :author, UserDto
endYou can skip certain fields from being assigned during updates:
# This is automatically included
class User < ApplicationRecord
castkit_ignored_on_update :id, :status
end:replace— full object replacement (default):merge— performs recursive merging viaupdate_from_dataobject!on nested models
to_model→ Instantiates a model from the DTO
to_dataobject(UserDto)update_from_dataobject(dto, mode: :replace, ignore: [])update_from_dataobject!(dto, mode: :replace, ignore: [])
MIT. See LICENSE.
Created with ❤️ by Nathan Lucas