如何让Rails定期调用控制器方法

时间:2013-09-11 23:36:41

标签: jquery ruby-on-rails ruby ajax

我有一个应用程序依赖于在其控制器中进行Web服务调用来获取数据。我想添加一个功能,页面会自动刷新内容,即根据一段设定的时间段调用操作。我发现很多帖子提示我的问题,我已经尝试了setInterval,令我感到困惑的是,每次更新都会解雇两次。这是代码:

$(document).ready(
  function(){
    var loader = function(){
      $('.container').load('/dashboard/index');
    };
    setInterval(loader, 3000);
  });

我觉得这是一个ajax问题,但我没有触发事件来发出更新信号。任何帮助表示赞赏。

我的控制器代码:

class DashboardController < ApplicationController
  include ActionView::Helpers::NumberHelper
  include FakeMaker

  def index
    @reports = fake_maker("report", 22)
    @workstations = fake_maker("workstation", 8)
    @data_sources = fake_maker("data_source", 2)
  end
end

FakeMaker类

module FakeMaker
  SOURCE_A = "A"
  SOURCE_B = "B"
  TYPES_A = Faker::Lorem.words(num = 10)
  TYPES_B = Faker::Lorem.words(num = 4)

  def fake_maker(type, count)
    fake = []
    case type
    when "report"
      count.times { fake << fake_report }
    when "workstation"
      count.times { fake << fake_workstation }
    when "data_source"
      fake = fake_data_source
    end
    fake
  end

  def fake_report
    report = { source: [SOURCE_A, SOURCE_B].sample,
               count: number_with_delimiter(Faker::Number.number(5), :delimiter => ',') }
    report[:type] = report[:source] == SOURCE_A ? TYPES_A.sample : TYPES_B.sample.capitalize
    report
  end

  def fake_workstation
    { name: Faker::Lorem.word,
      downloaded: number_with_delimiter(Faker::Number.number(3), :delimiter => ','),
      available: number_with_delimiter(Faker::Number.number(5), :delimiter => ','),
      last_connect: Random.rand(10.weeks).ago.strftime("%Y-%m-%d %H:%M:%S") }
  end

  def fake_data_source
    data_sources = []
    ["A", "B"].each do |source|
      data_sources << { type: source,
                        name: Faker::Internet.url,
                        status: ["UP", "DOWN"].sample }
    end
    data_sources
  end
end

1 个答案:

答案 0 :(得分:1)

你可以这样试试吗

$(document).ready(
  function(){
    setInterval(function(){
       $('.container').load('/dashboard/index');
    }, 3000);
  });