user1066568
user1066568

Reputation: 747

Issue with sorting a json array in Ruby

I have a ruby expression that builds a json array as follows

<%= raw((Object.listA | Object.listB).map { |s| {s.id.to_s => s.name} }.reduce(Hash.new, :merge).to_json)%>

In the expression above, Object is an ActiveRecord which has 2 attributes called listA and listB. Each one of these lists is a list of objects with an id and name. I want to merge these 2 lists and then sort the final list by name. I have tried doing the following but I'm unable to get a sorted list by name.

<%= raw((Object.listA | Object.listB).sort_by{ |s| s.name}.map { |s| {s.id.to_s => s.name} }.reduce(Hash.new, :merge).to_json)%>

Upvotes: 0

Views: 75

Answers (1)

spickermann
spickermann

Reputation: 106952

I would do something like this:

Object.listA.merge(Object.listB)
            .sort_by(&:name)
            .map { |o| { o.id.to_s => o.name } }
            .to_json

I am not sure what you try to achieve with the reduce(Hash.new, :merge) method call. Furthermore, I suggest following Ruby naming conventions (variables and method name in underscore instead of camelcase) and moving complex method chains like these from the view into the model or a helper.

Upvotes: 1

Related Questions