ビューにテーブルがあります: 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'
ネットワークのプレビュー タブ:
プレビュー タブ: