これにajaxアップデートを使用できます。ただし、信頼できないためページを終了するときにこの更新プログラムを起動する必要はありません(async
を無効にすると効果があります)。代わりに、レコードを更新するために定期的にAjaxの更新をポーリングする必要があります(10秒ごとに言う)。以下は私の提案する解決策です。
VideosController:
def show
video = Video.find(params[:id])
# Assuming Video belongs_to User, User has two fields called started_watching_at and duration
video.user.update_attribute(:started_watching_at, [current_time])
video.user.update_attribute(:watching_duration, 0)
end
# This method is to update user watching time
def touch_duration
video = Video.find(params[:id])
# Calculate time different then convert to duration
duration = [current_time] - [started_watching_at]
video.user.update_attribute(:watching_duration, duration)
respond_to do |format|
format.js { render nothing: true }
end
end
あなたのjsファイルでは、基本的にtouch_duration
メソッドを使用して、更新ユーザー・レコードをポーリングします。このような何か:
$(function() {
var time_to_check = 10000;
setInterval(time_to_check, touch_duration);
function touch_duration() {
// Update user
$.ajax({
url: // update url,
method: "PUT"
}, function(data) {
console.log("Successfully update!");
});
}
})
更新日:私はあなただけの映像ショーのページ内にAjaxの更新を実行することを言及するのを忘れてしまいました。私はあなたが簡単にそれを働かせることができると思います。
あなたの質問にお答えします。乾杯!
これは本当にうまく見えます。これにより、ビデオが一時停止されても監視された時間が追加され続けますか? – Doughtz
はい、あなたがページにとどまっている限りです – kasperite