我的视图中有一张表:views/uploads/index.html.erb
other code
<div id="uploads_table">
<table class="table table-striped">
<thead>
<tr>
<th>File name</th>
blah
blah
blah
<th>Actions</th>
</tr>
</thead>
<tbody >
<%= render (@uploads) %> <%# partial _upload.html.erb %>
</tbody>
这是部分“_upload.html.erb”
<tr id= "uploads_table_rows">
<td> <%= upload.sourcedata_file_name%></td>
<% path_arr = upload.f_path.split("\/")%>
blah
blah
blah
<%end%>
<td><%= render 'button', :upload => upload%></td>
</tr>
我试图在后台作业运行并且表中的值发生变化时更新此表。
为此,我有以下设置: 1)在我的 upload_controller.rb 中,我有以下方法:
before_action :set_upload, only: [:show, :edit, :update, :destroy]
#refresh uploads table in uploads/index.html.erb
def refresh_table
@uploads = Upload.all
@uploads.each do |u|
if(File.exist?(u.f_path))
puts "File #{u.sourcedata_file_name} exists"
else
puts "File #{u.sourcedata_file_name} has been removed"
u.update!(:status => "-1")
end
end
@uploads = Upload.all
respond_to do |format|
format.js
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_upload
@upload = Upload.find(params[:upload][:id])
end
# Only allow a trusted parameter "white list" through.
def upload_params
params.require(:upload).permit(:id, :sourcedata, :task_id, :status, :f_path, :job)
end
2)在我的 uploads.js.coffee 我添加了这段代码
$(document).ready ->
# will call refresh_table every 1 second
setInterval refresh_table, 1000
refresh_table = ->
$.ajax url: "/uploads_controller/refresh_table"
3)我用以下代码添加了一个文件'refresh_table.js.erb'
$('#uploads_table').html("#{escape_javascript(render 'upload', data:@uploads)}");
4)最后我用这一行作为最后一行更新了我的路线文件:
get 'uploads_controller/refresh_table'
我重新启动了服务器并启动了更新表值的后台作业。我在 chrome 中运行了 javascript 控制台,我看到的只是每 1 秒出现一次这些行
GET http://localhost:3000/uploads_controller/refresh_table 404 (Not Found)
jquery.js?
body=1:8707
我不确定出了什么问题。我是 AJAX 新手,所以我想知道是否有人可以帮我解决这个问题。谢谢
更新:尝试下面发布的解决方案后,我的 routes.rb 如下所示:
blah
blah
resource :uploads do
member do
post "parse"
get "refresh_table", to: "refresh_table"
end
end
blah
blah
这是在我的 chrome 浏览器中看到的“网络”选项卡的图像:
控制台选项卡如下所示:
服务器控制台输出:
Started GET "/uploads/refresh_table" for 127.0.0.1 at 2014-01-01 10:24:42 -0500
Processing by UploadsController#show as */*
Parameters: {"id"=>"refresh_table"}
Completed 500 in 1ms
NoMethodError - undefined method `[]' for nil:NilClass:
app/controllers/uploads_controller.rb:89:in `set_upload'
网络预览标签:
预览选项卡: