Ajax不会更新数据库中的属性

时间:2019-05-27 11:39:19

标签: javascript html ruby-on-rails ruby ajax

一堂课被完全观看后,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

3 个答案:

答案 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
  • 使用rails helper,它将帮助您在分段顺序,变量,named_routes等方面保持一致

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>
  • 我将URL作为#video元素的数据属性进行传递,因此我不必用JavaScript弄乱URL,让rails处理这些事情,这真的很不错

js

$('#video').onended(function() {
  $.ajax({
    url: this.dataset.viewedUrl,
    type: 'patch'
 });
});
  • 从元素的data属性获取URL

答案 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
 });
});