Sunday, 18 August 2013

Mark task as complete

Mark task as complete

Simple to-do list application. Having difficulty marking tasks as complete
without ajax. My approach was to create a "completed" column in the task
model which is a boolean. Then define complete and incomplete tasks in the
controller and create routes accordingly. This does not seems to work and
i am not sure why. Can someone let me know if i am doing it wrong ? I am
open to suggestions and alternatives please. cheers.
Task model with scoped options.
class Task < ActiveRecord::Base
validates_presence_of :title
#validates_presence_of :user_id
default_scope -> { order('created_at DESC') }
belongs_to :user
scope :completed, where(:completed =>true)
scope :incomplete, where(:completed =>false)
end
Routes file
match '/tasks/complete/:id' => 'tasks#complete', as: 'complete_task', via:
:put
match '/tasks/complete/:id' => 'tasks#incomplete', as: 'incomplete_task',
via: :delete
Tasks controller
def complete
@task = current_user.tasks.find(params[:id])
@task.completed = true
@task.save
redirect_to current_user
end
def incomplete
@task = current_user.tasks.find(params[:id])
@task.completed = false
@task.save
redirect_to current_user
end
Tasks index View
<h3>Incompleted tasks</h3>
<% current_user.tasks.incomplete.each do |task| %>
<p><%= task.title %>|
<%= link_to "Done", complete_task_path(task), method: :put %></p>
<% end %>
<h3>Completed tasks</h3>
<% current_user.tasks.completed.each do |task| %>
<p><%= task.title %>|
<%= link_to "Undo", incomplete_task_path(task), method: :delete %></p>
<% end %>
Also i am running rails 4.

No comments:

Post a Comment