The project is in a healthy, maintained state
Provides conversion helpers to serialize and deserialize between ActiveRecord models and Castkit DataObjects. Supports nested DataObjects, eager loading, and ActiveRecord-safe hydration.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

 Project Readme

Castkit ActiveRecord

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.

Installation

bundle add castkit-activerecord

Usage

Setup

Include 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
end

Converting a Model to a DTO

user_dto = UserDto.from_model(User.find(1))

Converting a DTO to a Model

user_model = user_dto.to_model

Updating a Model from a DTO

user.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 Support

Nested dataobject and has_many/has_one relationships are supported:

class PostDto < Castkit::DataObject
  include Castkit::ActiveRecord
  model Post

  string :title
  dataobject :author, UserDto
end

Opting Out of Attribute Updates

You can skip certain fields from being assigned during updates:

# This is automatically included
class User < ApplicationRecord

  castkit_ignored_on_update :id, :status
end

Update Modes

  • :replace — full object replacement (default)
  • :merge — performs recursive merging via update_from_dataobject! on nested models

Methods

On Castkit::DataObject

  • to_model → Instantiates a model from the DTO

On ActiveRecord::Base

  • to_dataobject(UserDto)
  • update_from_dataobject(dto, mode: :replace, ignore: [])
  • update_from_dataobject!(dto, mode: :replace, ignore: [])

📃 License

MIT. See LICENSE.


🙏 Credits

Created with ❤️ by Nathan Lucas