Even though I've come across several similar questions, I'm still struggling to make mine work correctly. Here's what my code looks like...
#app/views/tasks/index.html.erb
<%- @tasks.each do |task| %>
<div class="task-wrapper">
<%= check_box_tag 'checked_in', task.id , task.checked_in, :class => "task-check" %>
<%= content_tag :span, task.name %>
</div>
<% end %>
<%= link_to 'New Task', new_task_path %>
<script>
$(".task-check").bind('change', function(){
if (this.checked){
$.ajax({
url: '/tasks/'+this.value+'/toggle',
type: 'POST',
data: {"checked_in": this.checked}
});
}
else {
alert("no");
}
});
</script>
#app/controllers/tasks_controller.rb
...
def toggle
@task = Task.find(params[:id])
if @task.update_attributes(:checked_in => params[:checked_in])
# do I need something here?
else
# do I need something here?
end
end
...
In my task model, I have a 'checked_in' attribute that is boolean.
The source of this code was inspired by the following question...
Rails change boolean value with checkbox and jquery ajax
...and although I took reference from it, I am still unsure about some parts. While creating a new task, I can successfully mark the box checked to set my boolean value as true. However, when I uncheck the box, I receive a JavaScript pop-up saying "No", but nothing gets updated in the database and no information is sent back to the server.
Can anyone provide any insights or solutions?