Skip to content

Instantly share code, notes, and snippets.

@rwarbelow
Last active February 5, 2016 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwarbelow/73301b9f2bfb07ec5b6c to your computer and use it in GitHub Desktop.
Save rwarbelow/73301b9f2bfb07ec5b6c to your computer and use it in GitHub Desktop.
Adding Categories to Task Manager

Adding Categories to Task Manager

First, delete both task_manager_development.sqlite3 and task_manager_test.sqlite3. Then make sure you have the following code in your migration file (001_create_tasks.rb):

require 'sequel'

environments = ["test", "development"]

environments.each do |env| 
  Sequel.sqlite("db/task_manager_#{env}.sqlite3").create_table(:tasks) do
    primary_key :id
    String :title
    String :description
  end
end

Next, we'll add a table for categories with 002_create_categories.rb. Notice that we're still using the task_manager_#{env}.sqlite3 database, not creating a brand new database. After running this migration, you'll have a categories table in addition to your original tasks table. The second-to-last line of this migration will add a category_id column to the tasks table. This is how we will associate tasks with categories.

require 'sequel'

environments = ["test", "development"]

environments.each do |env| 
  database = Sequel.sqlite("db/task_manager_#{env}.sqlite3")
  database.create_table(:categories) do
    primary_key :id
    String :name
  end

  database.add_column :tasks, :category_id, :integer
end

Make sure to run both of these migration files.

We call this a one-to-many relationship because one category can have many associated tasks, and a single task belongs to one category. For more on a one-to-many relationship, check out this post (scroll partway down to find one-to-many).

Let's modify our user_can_create_a_task_test.rb:

require_relative '../test_helper'

class UserCanCreateANewTask < FeatureTest
  def test_task_creation_with_valid_attributes
    category_manager.create(name: "School")
    category_manager.create(name: "Work")

    visit '/tasks/new'

    fill_in 'task[title]', with: 'Example Task'
    fill_in 'task[description]', with: 'Example Description'
    select "School", from: "category_id" # NOTE: this will be the HTML id of a select element

    click_button 'Submit'

    assert_equal '/tasks', current_path

    within '#tasks' do
      assert page.has_content?('Example Task')
      assert page.has_content?('School')
    end

    refute page.has_content?('Work')
  end
end

Now, use this test to drive out the development of creating a task that is associated with a category. You'll need to do some Googling and looking at documentation. Have fun!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment