Read more

Casting ActiveRecord scopes or instances to ActiveType extended model classes

Henning Koch
June 12, 2015Software engineer at makandra GmbH

When working with ActiveType you will often find it useful to cast an ActiveRecord instance to its extended ActiveType::Record variant.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Starting with active_type 0.4.0 Show archive.org snapshot you can use ActiveType.cast for this:

class User < ActiveRecord::Base
  ...
end

class SignUp < ActiveType::Record[User]
  ...
end

user = User.find(1)
sign_up = ActiveType.cast(user, SignUp)
sign_up.is_a?(SignUp) # => true

This is basically like ActiveRecord#becomes Show archive.org snapshot , but with fewer bugs and more consistent behavior.

You can also cast an entire relation (scope) to a relation of an ActiveType::Record:

adult_users = User.where('age >= 18')
adult_sign_ups = ActiveType.cast(adult_users, SignUp)
sign_up = adult_sign_ups.find(1)
sign_up.is_a?(SignUp) # => true
Posted by Henning Koch to makandra dev (2015-06-12 13:25)