Posted almost 5 years ago. Visible to the public. Repeats. Linked content.

Casting ActiveRecord scopes or instances to ActiveType extended model classes

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

Starting with active_type 0.4.0 you can use ActiveType.cast for this:

Copy
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, but with fewer bugs and more consistent behavior.

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

Copy
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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Henning Koch
Last edit:
about 3 years ago
by Henning Koch
Keywords:
relations
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more