在Rails控制器中呈现JSON数据

时间:2012-11-18 22:49:47

标签: jquery ruby-on-rails heroku

当我将它上传到Heroku时,我对本地主机和同一个应用程序之间的区别感到困惑。

我通过控制器方法动态渲染JSON,并使用AJAX请求在Javascript中抓取它。

在localhost上,它运行正常。但是,当我上传到Heroku时,它根本不起作用。不知道为什么会出现这种情况。是否与Heroku如何访问我的模型以及我的localhost如何区别?

以下是来自同一时间戳的两个调试输出:

工作:

  

在它之前是106.944877,现在是0,增量为   -84.07055608611111

不工作:

  

在它为0之前,现在为0,增量为0

以下是代码:

控制器方法#1:

# present data to grab for view work
# get/user_data
def user_inst_data
timestamp = params[:time_now]
user_id = params[:user_id]

before = fetch_data_at_time(user_id, timestamp)
after = fetch_data_at_time(user_id, (timestamp.to_i+3600))

response = Hash.new

response['before'] = before
response['after'] = after

render json: response.to_json
end

控制器方法#2:

def fetch_data_at_time(user_id, time_at)
  # convert time to object
  timestamp = Time.at(time_at.to_i)
  # break down timestamp right now
  year = timestamp.year
  month = timestamp.month
  day = timestamp.day
  hour = timestamp.hour+1 #we're 1-indexed

  # find data
  response = UserData.where(:user_id=>user_id, :year=>year, :month=>month, :day=>day, :hour=>hour).select('power')

  return response
end

javascript:

function real_time_update(){
  //this function will fake "real-time" updates by grabbing simulated data from the DB
  //continue to update component every 5 seconds
  setTimeout(real_time_update,5000);
  var time = Math.round(((new Date()).getTime())/1000);

  var targetURL = "get/user_data?time_now="+time+"&user_id="+<%= @user.id %>;

  var power_before = 0;
  var power_after = 0;

  // GET data with AJAX request, set function for successful return
  $.get(targetURL, function(data){
    power_before = data.before[0].power;
    power_after = data.after[0].power;

    // after getting data before and after, find increment between them, delta-naught
    var delta = power_after - power_before;

    // scale before power by a percentage based on how much time has elapsed since last hour
    var current_time = new Date();
    var minutes_passed = (current_time.getMinutes())*60;
    var seconds_passed = minutes_passed + (current_time.getSeconds());
    var percent_hour = seconds_passed/3600;

    // calculate increment
    var delta_change = delta*percent_hour;

    // DEBUG----
    console.log("Before it was "+power_before+", now it is "+power_after+" with increments of "+delta_change)

    //add to power_before and update html component
    var power_update = power_before + delta_change;

    // redraw component
    drawChart(power_update);
  })
}

0 个答案:

没有答案