boulder_ruby
boulder_ruby

Reputation: 39695

How to render json in rails as an array of arrays without the metatags -- (passing data into google charts api javascript)

In rails, this is an api response I'm currently generating as a response from /charts_json/south_carolina.json (for example)

[{"d_s":0,"name":"summerville"},{"d_s":1,"name":"hilton head island"},{"d_s":2,"name":"north myrtle beach"},{"d_s":1,"name":"spartanburg"},{"d_s":12,"name":"greenville, sc"},{"d_s":0,"name":"aiken"},{"d_s":6,"name":"columbia"},{"d_s":4,"name":"myrtle beach"},{"d_s":1,"name":"simpsonville"},{"d_s":1,"name":"lancaster, sc"},{"d_s":0,"name":"north augusta"},{"d_s":0,"name":"sumter"},{"d_s":0,"name":"rock hill"},{"d_s":1,"name":"beaufort, sc"},{"d_s":1,"name":"mount pleasant"},{"d_s":21,"name":"charleston"},{"d_s":1,"name":"clemson"},{"d_s":1,"name":"anderson, sc"}]

Now what I need to do is render the above like this, as a json document

[['0', 'summerville'], ['1', 'hilton head island'], ...etc... ]

For the benefit of the SO community and the clarification of the reader I'll include all the code I'm going to be using to make this work if and when I get this last thing handled

In addition to my charts_controller, I generated a charts_json_controller for responding to json requests--- an example of a controller method in that controller (this is a bit clunky but its ok for now as long as I get functionality)

def south_carolina
    @locations = Location.find(1687).descendants #used acts_as_tree gem
    respond_to do |format|
      format.json { render json: @location.as_json(only: [:d_s, :name])}
end

In the view (cross section)

function drawMarkersMap() {
    var data = google.visualization.arrayToDataTable([
      ['Startups', 'Location'],
      $.ajax({url: '/charts_json/south_carolina', dataType: 'json'})
  ]);

Upvotes: 2

Views: 533

Answers (1)

muirbot
muirbot

Reputation: 2081

Not sure if I'm understanding correctly, but here's a way to get the json as an array instead of a hash.

define this method for Location

class Location
  def self.as_json_array
    as_json(only: [:d_s, :name]).collect { |l| [l[:d_s], l[:name]] }
  end
end

You could make this more general-purpose if you necessary, but I want to make sure I'm understanding your requirements first.

Then just use that method instead of as_json in your render line.

Also, it sounds like you know this, but you really should just use the same controller and put any custom code for different formats in your respond_to block.

Upvotes: 1

Related Questions