To create a task management system with Ruby on Rails, you can follow these steps:
1. Set up a new Rails application by running the following command in your terminal:
“`
rails new task_management_system
“`
2. Change into the project directory:
“`
cd task_management_system
“`
3. Generate a Task model and migration file:
“`
rails generate model Task title:string description:text due_date:date completed:boolean
“`
4. Run the database migration to create the tasks table:
“`
rails db:migrate
“`
5. Open the `app/models/task.rb` file and add the following validation for the title:
“`ruby
class Task < ApplicationRecord
validates :title, presence: true
end
“`
6. Generate a Tasks controller:
“`
rails generate controller Tasks
“`
7. Open the `config/routes.rb` file and add the following routes:
“`ruby
Rails.application.routes.draw do
resources :tasks
root ‘tasks#index’
end
“`
8. Open the `app/controllers/tasks_controller.rb` file and add the following actions:
“`ruby
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
def index
@tasks = Task.all
end
def show
end
def new
@task = Task.new
end
def create
@task = Task.new(task_params)
if @task.save
redirect_to @task, notice: ‘Task was successfully created.’
else
render :new
end
end
def edit
end
def update
if @task.update(task_params)
redirect_to @task, notice: ‘Task was successfully updated.’
else
render :edit
end
end
def destroy
@task.destroy
redirect_to tasks_url, notice: ‘Task was successfully destroyed.’
end
private
def set_task
@task = Task.find(params[:id])
end
def task_params
params.require(:task).permit(:title, :description, :due_date, :completed)
end
end
“`
9. Create the views for the tasks by creating the following files:
– `app/views/tasks/index.html.erb`
– `app/views/tasks/show.html.erb`
– `app/views/tasks/new.html.erb`
– `app/views/tasks/edit.html.erb`
10. Open the `app/views/tasks/index.html.erb` file and add the following code to display the list of tasks:
“`erb
Tasks
Title | Description | Due Date | Completed | |||
---|---|---|---|---|---|---|
<%= task.title %> | <%= task.description %> | <%= task.due_date %> | <%= task.completed ? ‘Yes’ : ‘No’ %> | <%= link_to ‘Show’, task %> | <%= link_to ‘Edit’, edit_task_path(task) %> | <%= link_to ‘Destroy’, task, method: :delete, data: { confirm: ‘Are you sure?’ } %> |
<%= link_to ‘New Task’, new_task_path %>
“`
11. Open the `app/views/tasks/show.html.erb` file and add the following code to display the details of a task:
“`erb
Title:
<%= @task.title %>
Description:
<%= @task.description %>
Due Date:
<%= @task.due_date %>
Completed:
<%= @task.completed ? ‘Yes’ : ‘No’ %>
<%= link_to ‘Edit’, edit_task_path(@task) %> |
<%= link_to ‘Back’, tasks_path %>
“`
12. Open the `app/views/tasks/new.html.erb` file and add the following code to create a new task:
“`