In backend, my object relationship is that an Item has_many Options. I'd like to be able to access all the attributes on the item and its child options as a hash in the front end:
items = [
{
id: 1,
item_attribute_name: item_attribute_value,
options: [
{id: 1, option_attribute_name: option_attribute_value},
{id: 2, option_attribute_name: option_attribute_value},
]
},
{
id: 2,
item_attribute_name: item_attribute_value,
options: []
}
]
I'm sending data either via a json object in response to an ajax request or using the handy gon gem. I noticed that if I were JUST interested in sending the parent items, the formatting automatically happens such that I can just send back Item.all and in the front end, get an array of items with each item being a hash that represents its attributes exactly as I want.
But if I want to send the children is there a standard way of doing it? I realize I can construct the child attributes myself as below, but wondering if there's a more straight forward direct way.
How I would make this work by constructing the child attributes:
items = Item.all
items.each do |i|
child_attr = {"options" => i.options }
i.attributes.merge(child_attr)
end
A totally acceptable answer, by the way, is that there's no... automagical way of doing this without doing what I'm doing now, which is converting each parent object to attributes in backend, and then stitching together the child attributes.
I'm only asking this question, frankly, because it'd be nice to keep the object relationships in the backend for reuse elsewhere, if possible, rather turning things into a hash.
I think the only way to get the expected result is with some monkey patching. So you can use a serializer, or include, or use ActiveModel::Serializers::JSON which is included by default in your models.
For exemple with ActiveModel::Serializers::JSON, you can do something like:
items = Item.all
items.map! do |i|
i.serializable_hash(include: { options: {} })
end
This is due to rails eager loading, which avoids having to load all children from an association(has_many for example). Where you'd like to serialize is up to your use case.