Reputation: 91
I'm trying to call an ajax method on my index page which updates an attribute. The attribute is updated (successfully) on a page refresh as the task (this is for a to do list app) is moved from the incomplete list to the complete list. However, when calling the ajax request using a button click, I receive the following error on my rails console:
ActiveRecord::RecordNotFound (Couldn't find Task with 'id'=:id [WHERE "tasks"."user_id" = ?]):
app/controllers/tasks_controller.rb:47:in `complete'
Here is my ajax request:
$(document).ready(function() {
console.log("working");
$('.task_submit_box').click(function() {
$.ajax({url: 'tasks#complete', type: "PATCH", success: function(result) {
$('.task_area').html(result);
console.log('test');
}});
});
});
my controller method:
def complete
@task = current_user.tasks.find(params[:id])
@task.update_attribute(:completed_at, Time.now)
@task.update_attribute(:completed, true)
redirect_to root_path
end
My index page area where it should be updated:
<ul class="wrapper_task_list">
<% @task.each do |task| %>
<% if task.completed == false %>
<li>
<div class="task_area", id="incomplete_task_area">
<%= link_to task.title, task_path(task), class: 'wrapper_task_name'%>
<%= form_for task, remote: true do |f| %>
<%= f.check_box :completed, class: 'task_check_box' %>
<%= f.submit 'update', class: 'task_submit_box' %>
<% end %>
</div>
</li>
<% end %>
<% end %>
</ul>
I'm lost in trying to match the ajax request with the correct task/:id. my routes specifically mention the url listed in the ajax request:
PATCH /tasks/:id/complete(.:format)
Upvotes: 0
Views: 165
Reputation: 230336
$.ajax({url: 'tasks#complete'
You seem to be using Rails' route syntax here. Those are not valid urls. Your url must look like this:
url: "/tasks/1/complete"
where number should be dynamic, of course. (hint: just fetch form's action
attribute and use that as url).
See that remote: true
there? It means that you don't have to manually handle submit clicks. It will perform ajax for you. You just have to create a JS view, where you will do whatever it is you do when item is completed.
// views/tasks/complete.js.erb
$('#task-<%= @task.id %>').addClass('completed')
Section 14.2.5 of Michael Hartl's rails tutorial covers almost this exact scenario: ajax-powered button that changes something and changes have to be reflected on the page.
Upvotes: 1