Rails prototype Post-It: Lesson 1

This is what I have done on week 1, course 2 of Tealeaf Academy:

Database tables - schema view #

Migration files #

$ rails generate migration create_posts
$ rails g migration create_users
$ rails g migration add_user_id_to_posts
$ rails g migration create_comments
$ rails g migration create_categories
$ rails g migration create_post_categories

posts #

create_table
  t.string :url, :title
  t.text :description

users #

  t.string :username

add user_id to posts #

add_column :posts, :user_id, 'integer'

comments #

create_table
  t.text :body
  t.integer :post_id, :user_id

category #

  t.string :name

join table for many to many association of post and category #

  t.integer :post_id, :category_id

for all do not forget #

  t.timestamps

build schema file and database #

$ rake db:migration

Model files #

post #

class Post < ActiveRecord::Base
  belongs_to :creator, foreign_key: 'user_id', class_name: 'User'
  has_many :comments
  has_many :categories, through: :post_categories
  has_many :post_categories
end

user #

  has_many :posts
  has_many :comments

comment #

  belongs_to :post, foreign_key: 'post_id'
  belongs_to :creator, foreign_key: 'user_id', class_name: 'User'

category #

  has_many :posts, through: :post_categories
  has_many :post_categories

post_category #

  belongs_to :post, foreign_key: 'post_id'
  belongs_to :category, foreign_key: 'category_id`

Controller files #

posts #

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end
end

Routes file #

  resources :posts, except: :destroy
 
1
Kudos
 
1
Kudos

Now read this

minitest setup - Ruby on Rails

I now do testing in Minitest. I came to think it’s better choice to start with minitest for testing Rails. And I thought it would make more sense when I stay out of Minitest::Spec. my-experience-with-minitest-and-rspec by tenderlove... Continue →