一堂课被完全观看后,Ajax不会更新已查看的属性。
application.js:
$('#video').onended(function() {
$.ajax({
url: '/courses/:id/lessons/:id/viewed',
type: 'patch'
});
});
课程控制器;
def viewed
@lesson = Lesson.find(params[:id])
@lesson.update_attribute(:viewed, true)
end
教训/show.html.erb:
<h2><%= @lesson.name %></h2>
<div id="video">
<video controls="true" width="auto" height="auto">
<source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
</video>
</div>
config / routes.rb:
patch 'courses/:id/lessons/:id/viewed' => 'lessons#viewed'
add_view_to_lessons迁移:
def change
add_column :lessons, :viewed, :boolean
end
答案 0 :(得分:0)
转换
patch 'courses/:id/lessons/:id/viewed' => 'lessons#viewed'
到
patch 'courses/:course_id/lessons/:id/viewed' => 'lessons#viewed'
和
$('#video').onended(function() {
$.ajax({
url: '/courses/:id/lessons/:id/viewed',
type: 'patch'
});
});
到
const data = { course_id: "", lesson_id: "" }
$('#video').onended(function() {
$.ajax({
url: '/courses/:course_id/lessons/:id/viewed',
type: 'patch',
data: data
});
});
和
def viewed
@lesson = Lesson.find(params[:id])
@lesson.update_attribute(:viewed, true)
end
到
def viewed
@lesson = Lesson.find(params[:data][:lesson_id])
@lesson.update_attribute(:viewed, true)
end
答案 1 :(得分:0)
我会做这样的事情:
routes.rb
resources :lessons do
member do
patch :viewed
end
end
show.html
<h2><%= @lesson.name %></h2>
<div id="video" data-viewed-url="<%= viewed_lesson_path(@lesson) %>">
<video controls="true" width="auto" height="auto">
<source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
</video>
</div>
#video
元素的数据属性进行传递,因此我不必用JavaScript弄乱URL,让rails处理这些事情,这真的很不错js
$('#video').onended(function() {
$.ajax({
url: this.dataset.viewedUrl,
type: 'patch'
});
});
答案 2 :(得分:0)
首先,让我们修复路线:
path "/lessons/:id/viewed" => "lessons#viewed", as: :lesson_viewed
除非是实际路线,否则我们不需要课程ID,除非我们实际上对该信息进行了有用的操作。
我建议您在erb中添加一个data
属性以指定呼叫路径
<h2><%= @lesson.name %></h2>
<div id="video" data-lesson-viewed-url="<%= lesson_viewed_url(@lesson.id) %>">
<video controls="true" width="auto" height="auto">
<source src="<%= url_for(@lesson.file) %>" type='video/mp4'>
</video>
</div>
请注意<div id="video" data-lesson-viewed-url="<%= lesson_viewed_url(@lesson.id) %>">
行中的更改。
现在Ajax可以简单地调用该路由:
$('#video').onended(function() {
$.ajax({
url: $('#video').data("lesson-viewed-url"),
type: 'patch' // Can move the HTTP verb to data attribute as well, leaving this upto the implementor for now
});
});