Home ActiveRecord::Type::Value casting in Rails 4
Reply: 0

ActiveRecord::Type::Value casting in Rails 4

MoMolog Published in 2018-01-02 14:23:48Z

We want to use the Whole Value pattern in our Rails4 application.

We know that in Rails5, if we want OurModel to use a custom NameType Whole Value type for the attribute :name, we can define our custom type similar to this:

class NameType < ActiveModel::Type::Value
  def cast(value)

  def serialize(value)

and then in OurClass

class OurClass < ApplicationRecord
  attribute :name, NameType.new

which provides us with completely transparent serialization when saving the model to the DB and casting to the Whole Value Type when creating the model from the DB or manually (this is described in this RubyTapas episode, subscriber-only).

Can something similarly elegant be achieved in Rails 4? If so, how?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.337298 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO