简体   繁体   中英

Difference between objects in views in Ruby on Rails

does anybody know the difference between the object on the initial show.html.erb in Rails and the index.html.erb ? The reason I'm asking is because I'm using the javascript library d3.js and for that I need a json-object. In all index.html.erb I can create them with calling:
<% @commits.to_json %> but if I try to use that statement in any show.html.erb the browser tells me that the result is just an object (seems not to be a json) so that I later can't call forEach (that I need to call).

Thanks in advance!

Ok, for a better understanding I append more code:

<%= javascript_tag do %>

d3.json('<% @commit.jobs.to_json %>', 
            function(data){


      var margin = {top: 20, right: 80, bottom: 30, left: 50},
          width = 960 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;

      var format = d3.time.format("%Y-%m-%dT%H:%M:%SZ");

      //parse time format correct
      data.forEach(function(d) {
          console.log(d.finished_at);
          d.finished_at = format.parse(d.finished_at);
          console.log(d.finished_at);
        });

   //more code!     


<% end %>

The problem is, I have a commit object in show.html.erb that has belonging jobs and now I want to visualize the belonging jobs with d3.js . I tested if this: @commit.jobs.to_json creates a valid json and it does! But the console throws an error: Uncaught TypeError: Object #<Object> has no method 'forEach'

What am I doing wrong?

In show you usually have only one @commit that you are showing.

In index you usually have all @commits as an array of objects.

def index
   @commits = Commit.all # all
end

def show
   @commit = Commit.find(params[:id]) # only one
end

if you want all commits in the show.html.erb do <%= Commit.all.to_json %>

So there are technically no differences between the objects based on the view they are in. They just mean different ( @commit , @commits ) things based on how they got initialized in the method before calling the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM