Reputation: 76
I am a beginner programmer trying Ruby on Rails.
I have added sortable UI into my to-do list application. I am able to drag and drop the list-items, but did not managed to get the new positions persist in the database.
The debugger on my Safari browser showed the error when I drag and drop list-items:
ReferenceError: Can't find variable: Rails
I was following this tutorial: https://www.youtube.com/watch?v=Aru-XvzzGjU
My guess is the task.js file which variable Ruby on Rails is not found. The error goes away when I move the jQuery script below the jQuery UI script, but is prompted another error
uncaught typeerror: $(...).sortable is not a function
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'),
});
}
}
);
});
//= 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">
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
Upvotes: 2
Views: 2275
Reputation: 76
I realised I just have to add this in the application.js file:
//= require rails-ujs
Upvotes: 2