Reputation: 357
I have the following method in my Rails app which works very well. Basically, I grab a bunch of objects (event
, captable
and shareholders
) and just merge them into one @snapshot
object and then convert that to_json
and put it in the database.
def save_captable_snapshot(transaction)
@transaction = transaction
@event = @transaction.event
@captable = @transaction.captable
@shareholders = @captable.company.shareholders
@snapshot = []
@snapshot.push(@captable, @event, @shareholders)
@event.update_attribute(:snapshot, @event.snapshot = @snapshot.to_json)
end
If I spit out an @event.snapshot in a view, I get the following JSON.
[
{
"id":27,
"total_stocks_in_company":"100.0",
"version":1,
"name":"cap table ",
"company_id":20,
"created_at":"2018-10-25T18:35:13.413Z",
"updated_at":"2018-10-25T18:35:54.431Z"
},
{
"status_locked":null,
"id":45,
"price_per_share":"100.0",
"total_company_stocks_after_event":"100.0",
"name":"funding",
"date":"2018-10-25",
"currency":"",
"valuation":"10000.0",
"created_at":"2018-10-25T18:35:19.273Z",
"updated_at":"2018-10-25T18:35:54.447Z",
"captable_id":27,
"company_id":20,
"snapshot":null
},
[
{
"id":0,
"shareholder":"Bob",
"name":"Bob",
"number_of_stocks":null,
"company_id":20,
"created_at":"2018-10-25T18:33:20.770Z",
"updated_at":"2018-10-25T18:33:20.770Z",
"ownership_percentage":null,
"email":"",
"telephone":""
},
{
"id":48,
"shareholder":"Peter",
"name":"Peter",
"number_of_stocks":"100.0",
"company_id":20,
"created_at":"2018-10-25T18:33:33.109Z",
"updated_at":"2018-10-25T18:35:54.437Z",
"ownership_percentage":"1.0",
"email":"",
"telephone":""
},
{
"id":49,
"shareholder":"BobJane",
"name":"BobJane",
"number_of_stocks":null,
"company_id":20,
"created_at":"2018-10-25T18:33:45.695Z",
"updated_at":"2018-10-25T18:33:45.695Z",
"ownership_percentage":null,
"email":"",
"telephone":""
}
]
]
As you can see, there is no formatting on the object, so working with it is cumbersome. What I'd like to achieve is something like the following (pseudo-code).
{
"captable":{
"id":2,
"name":"A Great Captable"
},
"event":{
"id":24,
"name":25,
"number of stocks":3040
},
"shareholders":[
{
"id":345,
"name":"Bob",
"ownership percentage":0.45
},
{
"id":345,
"name":"Bob",
"ownership percentage":0.45
},
{
"id":345,
"name":"Bob",
"ownership percentage":0.45
}
]
}
I've tried a bunch of different things but cannot get the three "headings" into the JSON object successfully - the three headings or sections being captable
, event
and then each shareholder
.
How would I best set up an empty object and then push in my three objects into the object before saving it to the database?
Upvotes: 0
Views: 139
Reputation: 538
Use hash instead of Array:
@snapshot = {
captable: @captable,
evet: @event,
shareholders: @shareholders
}
Upvotes: 3