Using one
to serialize an active record serialized field
#203
-
Hello there, I chose to use Alba after evaluating many other options. So first, I want to say a big thank you. I'm currently developing a new API for a resource that contains many ActiveRecord serialized types, such as a money object. Money creates at least two fields: Let's suppose a Product object that has that fields. I got the following working but feels odd to use class Product < AR::Base
monetize :price_cents
end
class MoneyResource
include Alba::Resource
attribute :cents do |money|
money.cents
end
attribute :currency do |money|
money.currency_as_string
end
attribute :formatted do |money|
money.format
end
end
class ProductResouce
include Alba::Resource
attributes :id, :name
one :price, resource: MoneyResource
end I'm aiming to produce an output like the below: {
id: 1,
name: "Foo",
price: {
cents: 1000,
currency: "USD",
formatted: "$10,00",
}
} The next step is, let's say that, for historical reasons, the attribute from Again, thank you. I appreciate it if you can shed some light on this. 😊 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Thinking more about that, what would you think of using the following: class ProductResouce
attribute :price do |product|
MoneyResource.new(product.suggested_price).to_h
end
end |
Beta Was this translation helpful? Give feedback.
-
Hi!
It can be read as "Product has one price." Personally it's acceptable, but if you want to avoid that then you could use the code like you posted later.
You can add |
Beta Was this translation helpful? Give feedback.
Hi!
It can be read as "Product has one price." Personally it's acceptable, but if you want to avoid that then you could use the code like you posted later.
You can add
key
option toone
method to change its key. See https://rubydoc.info/gems/alba/Alba/Resource/ClassMethods#association-instance_method(Sorry that it's not in README, I'll add the mention to it)