Skip to content

Instantly share code, notes, and snippets.

@ttanimichi
Last active October 1, 2015 05:37
Show Gist options
  • Select an option

  • Save ttanimichi/6479bb8e51e1418c7574 to your computer and use it in GitHub Desktop.

Select an option

Save ttanimichi/6479bb8e51e1418c7574 to your computer and use it in GitHub Desktop.
  • Category has_many topics
  • Topic has_many posts
# app/models/category.rb

class Category < ActiveRecord::Base
  has_many :topics

  validates :name, presence: true, length: { maximum: 255 }
  validates :code, presence: true, length: { maximum: 255 }
end
# db/migrate/20150927131959_create_categories.rb

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :name, null: false
      t.string :code, null: false

      t.timestamps null: false
    end

    add_index :categories, :name, unique: true
    add_index :categories, :code, unique: true
  end
end
require 'test_helper'

class CategoryTest < ActiveSupport::TestCase
  should have_many(:topics)

  should validate_presence_of(:name)
  should validate_presence_of(:code)

  should validate_length_of(:name).is_at_most(255)
  should validate_length_of(:code).is_at_most(255)

  should have_db_column(:name).of_type(:string).with_options(null: false)
  should have_db_column(:code).of_type(:string).with_options(null: false)
  should have_db_column(:created_at).of_type(:datetime).with_options(null: false)
  should have_db_column(:updated_at).of_type(:datetime).with_options(null: false)

  should have_db_index(:name).unique(true)
  should have_db_index(:code).unique(true)
end
class Topic < ActiveRecord::Base
  has_many :posts

  validates :name, presence: true, length: { maximum: 255 }
  validates :code, presence: true, length: { maximum: 255 }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment