Skip to content
Dave Strus edited this page Jul 16, 2015 · 1 revision

Our app is shaping up nicely, but there are still some things missing. Wouldn't it be grand to assign posts to categories? Let's make it happen!

So, how do we do it?

Category could be another enum on Post. That would be a very quick solution, but it would be a nightmare to maintain. Any change in the available categories would mean an update to code.

It makes more sense to make a separate model for categories.

It doesn't really need any attributes besides name at the moment, so we could keep our migration super-simple. We will go ahead and include a few more fields that we'll use down the road anyway.

We won't put size limits on our strings at the database level. We'll just enforce those in our model. With PostgreSQL, it makes no difference in terms of performance or storage. (It does have an effect on how much storage is used in MySQL).

Database constraints are still useful for various reasons, including scenarios in which other apps are writing to the same database without going through a shared API. For our purposes, the flexibility that comes with managing it within Rails outweighs such concerns.

When invoking the migration generator, we'll use the shortcut g in place of generate.

$ bin/rails g migration create_categories
      invoke  active_record
      create    db/migrate/20141104201700_create_categories.rb

Edit your migration as follows:

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :name
      t.string :title
      t.text :description
      t.text :sidebar
      t.text :submission_text
      t.timestamps
    end
  end
end

Then run that sucker!

$ bin/rake db:migrate
== 20141104201700 CreateCategories: migrating =================================
-- create_table(:categories)
   -> 0.0134s
== 20141104201700 CreateCategories: migrated (0.0135s) ========================

Now let's create the model.

LAB

Create the Category Model

Include validations that enforce the following:

  • name is a required field
  • name cannot exceed 20 characters
  • title cannot exceed 100 characters
  • description cannot exceed 500 characters
  • sidebar cannot exceed 5120 characters
  • submission_text cannot exceed 1024 characters

SOLUTION

app/models/category.rb

class Category < ActiveRecord::Base
  validates :name, length: { maximum: 20 }, presence: true
  validates :title, length: { maximum: 100 }
  validates :description, length: { maximum: 500 }
  validates :sidebar, length: { maximum: 5120 }
  validates :submission_text, length: { maximum: 1024 }
end

Try creating some categories from the console. If all is well, go head and commit.

$ git add .
$ git commit -m "Add Category model."