Long time no see 🙂 sometimes I feel like I should tell that to myself as well.
So how do we start, we start by noting down what we need to do, and while we are at it, we note down what we didn’t write in the first place and also few more things which you should have thought of before. To do things is to improvise, learn and also to keep on adding more things to do, obviously a to-do list never ends, because to do something or to learn something, you need to do a lot of things 🙂
To understand that lets write a blog post 🙂 This is going to be quick. All you need is rails setup in your system.
Lets start with creating a blank app
rails new todoapp # this will create a blank slate for you to work on
rails g scaffold todo task:string complete:boolean parent_task_id:integer # this will create your model/views/controller/migration etc etc files which you will do the work for you
rake db:migrate # if this throws an error, you gotta do “rake db:setup first” this will create your database migration and the schema for todo tasks.
Now we need to build something like the below to sorta have a parent child relationship between the tasks. Why ? just read the 2nd para again from top.
Parent Task 1
—- Child Task 1
—- Child Task 2
Parent Task 2
Parent Task 3
—- Child Task 1
——– Child Task 2
In your new and shiny app/models/todo.rb add these two lines to create the parent child hierarchy.
has_many :child_tasks, :class_name => 'Todo', :foreign_key => "parent_task_id"
belongs_to :parent_task, :class_name => 'Todo', :foreign_key => "parent_task_id"
Now a bit of magic is needed to the views to allow us to easily select the Parent tasks for any child task.
Head over to your app/views/todos/_form.html.haml or *.erb file depending on the templating engine and change the f.parent_task_id to a
= f.label :parent_task_id
= collection_select :todo, :parent_task_id, Todo.all + [Todo.new], :id, :task
This will allow us to choose a parent task, whenever we are creating a new task with – not a very bad hack? 😛
Finally in the show and index page, we need to display the parent task.
Todo.find_by_id(@todo.parent_task_id).task rescue "No Parent Task"
And the end result is tada!!!