Ruby class 2011 02 22
A real rails app[edit]
What should we build?[edit]
A todo list application:
Models:[edit]
- Task
- id (integer, automatically generated)
- timestamps (datetime, automatically maintained)
- title (string)
- description (string)
- time_required (integer, 1-6)
- value (integer, 1-10)
- due_date (datetime)
- done_date (datetime)
- priority_item (boolean)
- Project
- id
- timestamps
- name
- description
- Tag
- id
- timestamps
- name
- description
Views:[edit]
Just one:
- Task list
- A table of tasks
- Entry fields at the top and bottom for new tasks
If we get around to it we can do:
- Projects & Tags page
- Project view
- Tag view
Controllers:[edit]
TasksController
- show
- create
- done
Let's begin[edit]
Run the following:
$ rails new rudo $ cd rudo $ rails generate model task
Then add the following lines to create_tasks migration:
create_table :tasks do |t| t.string :title t.string :description t.integer :time_required t.integer :value t.datetime :due_date t.datetime :done_date t.boolean :priority_item t.references :project # ^^ this is the same as t.integer :project_id t.timestamps end
Alright, now let's create the other migrations:
$ rails generate model project name:string description:string $ rails generate model tag name:string description:string $ rails generate model tagging
Now let's take a look at the migrations... See the fields automatically added to the migrations We'll need to modify the create_taggings migration, though:
create_table :taggings, :id => false do |t| # can also be t.integer :tag_id, :task_id t.references :tag t.references :task t.timestamps end
Okay, let's try to migrate:
$ rake db:migrate
Alright, now let's get our models associated:
app/models/task.rb[edit]
has_many :taggings has_many :tags, :through => :taggings belongs_to :project
app/models/tagging.rb[edit]
belongs_to :tags belongs_to :task
app/models/project.rb[edit]
has_many :tasks
And now our controller:
$ rails generate controller tasks
Edit the controller and add the methods we're going to want:
app/controllers/tasks_controller.rb[edit]
def show @tasks = Task.all end def create @task = Task.new(params[:task]) end def done Task.find(params[:id]).mark_done end
And now for our primary view:
app/views/task/show.html.erb[edit]
<h1> Tasks: </h1> <% @tasks.each do |task| %> <h3><%= task.title %></h3> Description: <%= task.description %></br> Due: <%= task.due_date %></br> Priority Item: <%= task.priority_item %></br> Project: <%= task.project.name %></br> Tags: <%= task.tags %></br> <% end %>
Okay, so now what? Ah, yes, routes. First:
$ rm public/index.html
Now, inside our routes file:
config/routes.rb[edit]
root :to => "tasks#show"
Alright, so now we have our view, but not much to see. Let's add some tasks from the console. But why not make it possible to do it from our page, seeing as how that's how it will get used. Let's look back at our scratch project.