ReferenceError:找不到变量:Rails

时间:2018-12-23 10:26:41

标签: jquery ruby-on-rails jquery-ui-sortable

我是尝试Ruby on Rails的初学者。

我已将可排序的UI添加到待办事项列表应用程序中。我可以拖放列表项,但没有设法使新位置保留在数据库中。

当我拖放列表项时,我的Safari浏览器上的调试器显示了错误:

  

ReferenceError:找不到变量:Rails

我正在关注本教程: https://www.youtube.com/watch?v=Aru-XvzzGjU

我的猜测是 task.js 文件,该文件找不到Ruby on Rails变量。当我将jQuery脚本移到jQuery UI脚本下方时,该错误消失了,但是提示另一个错误

  

未捕获的类型错误:$(...)。sortable不是函数

tasks.js:

document.addEventListener("turbolinks:load", function () {

  $("#tasks").sortable(
    {
      update: function(e, ui) {
        //console.log($(this).sortable('serialize'));
        Rails.ajax({
          url: $(this).data("url"),
          type: "PATCH",
          data: $(this).sortable('serialize'),
        });
      }
    }
  );
});

application.css:

//= require activestorage
//= require turbolinks
//= require_tree .
//= require jquery
//= require jquery_ujs
//= require jquery-ui/widget
//= require jquery-ui/widgets/sortable
//= require rails_sortable

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<%= stylesheet_link_tag "application" %>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
    crossorigin="anonymous">

task.rb:

class Task < ApplicationRecord
  validates :title, :description, presence:true
  acts_as_list scope: [:title, :description]
end

任务控制器:

class TasksController < ApplicationController
  # create new instance of the task
  def index
    @task = Task.order(:position)
  end

  def new
    @task = Task.new
  end

  def create
    #create a new instance
    @task = Task.new(task_params)
    @task.save

    #redirect to url
    redirect_to @task
  end

  def show
    find_task
  end

  def edit
    find_task
  end

  def update
    find_task
    @task.update(task_params)

    redirect_to @task
  end

  def destroy
    find_task.destroy

    redirect_to tasks_path
  end

  def sort

    params[:task].each_with_index do |id, index|
      Task.where(id: id).update_all({position:index + 1})
    end

    head :ok

  end

end

private
  def task_params
    params.require(:task).permit(:title, :description)
  end

  def find_task
    @task  = Task.find(params[:id])
    return @task
  end

1 个答案:

答案 0 :(得分:1)

我意识到我只需将其添加到 application.js 文件中:

  

// =需要rails-ujs