1

I'm trying to use d3-rails gem to use d3.js in my rails app.

I included both

gem "d3-rails"
gem "d3js-rails"

in my Gemfile.

The problem is, right now I have a index.html.erb page that just prints json (which I don't have, it's from a third party api db) in text format (without use of any d3). In place of the text format, I want some bar charts enabled by d3.js. I'm still pretty new to rails, so I'm quite confused.

  1. Right now I have access to a specific json value, say

    @parsed_data

and say that json contains the following data. Oh first of all, that json name -- @parsed_data -- I was able to successfully access through ruby language portion of my erb file, but how do I do the same in javascript for the sake of d3?

{
  "firstName": "John",
  "lastName": "Smith",
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021"
  },
  "phoneNumber": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "fax",
      "number": "646 555-4567"
    }
  ],
  "gender": {
    "type": "male"
  }
}

Knowing the structure of this JSON (but I don't have it sitting somewhere in my asset pipeline, it's from third party API), how would I use d3 in my current index.html.erb?

Do I need a separate javascript file for this? Can I embed it in my existing View file (index.html.erb) with script tag?

p.s. How I'm displaying the fetched JSON in text has nothing to do with d3. It just uses ruby language to parse through the JSON.

Here is the tutorial I tried to follow but without success. http://www.overfitted.com/blog/?p=302

Also other stackoverflow posts, but I'm not sure if I really need AJAX for this task. Wouldn't using a d3js-rails / d3-rails gem suffice? Also new to AJAX (crash-coursed through a few pages of reading, but still confused) so excuse me if I am saying something that might sound silly.

p.s.s. I have the following in my application.js.

//= require_tree
//= require d3
claude computing
  • 319
  • 3
  • 13

1 Answers1

3

It took me a while to parse your question, it's very broad. I think, there are two parts to your question, if I got that right.

How to pass data from rails to JavaScript

I was able to successfully access through ruby language portion of my erb file, but how do I do the same in javascript for the sake of d3?

To me it looks like you are not sure how to access data fetched through a third party API in your rails stack in your javascript.

There are several options, all explained in:

How to display data with d3.js

Knowing the structure of this JSON [...], how would I use d3 in my current index.html.erb?

Now, in order to display your data in d3.js, consult the question Loading D3.js data from a simple JSON string or do some research on your own.

I want some bar charts enabled by d3.js

There is a tutorial for that.

Good luck!

Community
  • 1
  • 1
iblue
  • 29,609
  • 19
  • 89
  • 128