Rails时钟显示

Rails clock display

我有一个应用程序需要在索引页上显示一个时钟。 所以我有一个这样的静态控制器:

controllers/static_controller.rb:

class StaticController < ApplicationController

  def index
    @time = Time.now.strftime("%H:%M:%S ")
  end

  def get_time
    @time = Time.now.strftime("%H:%M:%S ")
    render partial: "date"
  end

end

我在 views/static/index 上有这个。html.erb:

<div class="time-container">
   <%= render partial: "date" %>
</div>

而这个部分 views/static/_date.html.erb 只包含 var:

  <%=@time%>

我使用这个 JS 函数尝试在 assets/javascripts/static.js 上更新时间:

$(document).ready(function () {
    setInterval(function () {
        $('.time-container').load('/static/get_time');

    }, 1000);
});

我的routes.rb是这样的:

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root "static#index"
  resources :static

end

这样,时钟会在页面加载时显示,但它始终保持不变,不会更新。我错过了什么吗?

您的路线与您建立的流程不匹配。

你很幸运 static/index 起作用了,因为它包含在资源声明中。

取出:

resources :static

并替换为

get 'static/index'
get 'static/get_time'