开发者

Query rails database, and update highcharts using Javascript

I have a page which shows a highchar. I'd like to use Javascript to fetch several pieces of information for a specific user. I want to fetch from my database and place it on the highcharts graoh. I have set up a JSfiddle which shows static data. But

What I am trying to do is:

  • Make javascript call a Rails action with parameters.
  • Query the rails database(projectHours table).
  • Rails returns the response.
  • Javascript updates highcharts and maps the information stored in the projectHours table.

So my question is What if I want to use information from m开发者_如何学Pythony db?

Two of the following models

Effort.rb

class Effort < ActiveRecord::Base              
  belongs_to :project_task
  belongs_to :user
end

Users.rb

class User < ActiveRecord::Base

  has_many :projects
  has_many :efforts

A further note, I think that in my efforts controller I may need to add some form of render action

     rails reponds_to do |f| f.json 
    { render :json => some_hash
} 
      end


You can use jQuery's get function in order to send a GET request to your rails app like so

$.get("/efforts/24", { name: "John", time: "2pm" } );

And in your controller you could do something like

def show
  @effort = Effort.find(params[:id])
  # or find by some of the name of time params

  respond_to do |f|
    format.json { render :json => @effort }
  end
end

Depending on how you want to render the results you can either let javascript handle the ajax:success by adding in to the original jQuery get

$.get("/efforts/24", { name: "John", time: "2pm" } ).success(function(data) {
  alert(data)
  // Or do whatever you want :)
});

Or you can change the respond_to to

respond_to do |f|
  format.html { render :nothing => true }
  format.js
end

And create a show.js.erb in your app/views/efforts directorty. In this file you can use the responded object

$('body').html("<h1><%= escape_javaScript(@effort.title) %></h1>").append("
<%=escape_javaScript(@effort.content) %>");

Some good tutorials

Rails and jQuery jQuery GET

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜