L457
L457

Reputation: 1032

Using Rails 5 attributes api with hash virtual attributes

I have a hash store as follows:

store :order_details, accessors: %w{item_name, external_id, total......etc}, coder: JSON

I'm deserializing this to a ruby object using a lib class elsewhere with a couple of methods in it for validations/operations

I would like to make use of the rails 5 attributes api instead so that I could directly have:

attribute :order_details, Type::OrderDetailType.new

(plus it would make it easier to add validations to each field in my hash)

I've seen examples online for using rails5's attributes api for simple virtual attributes(strings, integers...etc), but have not come across any info on how to implement it for a hash attribute. Would appreciate it if someone could point me in the right direction.

Upvotes: 0

Views: 1643

Answers (1)

Raj
Raj

Reputation: 22926

Extend Type::OrderDetailType from ActiveRecord::Type::Value

You can override cast and serialize method.

def cast(value)
  value
end

def serialize(value)
  value
end

An example of Money type:

# app/models/product.rb
class Product < ApplicationRecord
  attribute :price_in_cents, MoneyType.new
end

class MoneyType < ActiveRecord::Type::Integer
  def type_cast(value)
    # convert values like '$10.00' to 1000
  end
end

product = Product.new(price_in_cents: '$10.00')
product.price_in_cents #=> 1000

Doc: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html

Example: http://nithinbekal.com/posts/rails-5-features/

Upvotes: 1

Related Questions