2015-05-20

Level Up - Ruby on Rails: How to create a very minimal blog website (two different ways)

As I was refreshing myself with Ruby on Rails, I've decided to share these notes. To follow these steps, you don't actually need to know any Ruby or Rails, but you should have them installed already. I'm using Ruby 2.1.5p273, Rails 4.2.0, Windows 8.1, but these steps are simple enough to do on any version.

I show two different ways to create a very code minimal blog. It also demonstrates the power of of Rails scaffolding.

Using scaffold


1. Just run the following commands one after another:

    rails new quick-blog
    cd quick-blog
    rails generate scaffold post title:string body:text
    rails generate scaffold comment post_id:integer body:text
    rake db:migrate

2. To create a post or comment, make sure that the `rails server` is started. Then, in browser, navigate to `/posts/new` or `/comments`.
3. Done


Without using scaffold


1. Run `rails new very-minimal-blog`
2. Run `cd very-minimal-blog`, then `rake db:create`
3. Create the model for the posts: Run `rails generate model Post title:string body:text`
4. Run `rake db:migrate`
5. Create a controller for the posts: Run `rails generate controller Posts`
6. In that controller that was just created in `app/controllers/posts_controller.rb`, add some code so that it looks like the following:

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

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

7. In `app/views/posts/`, create a new file called `index.html.erb` and add the following code:

   

Very Minimal Blog


    <% @posts.each do |post| %>
     

<%= post.title %>


      <%= link_to "Read me", post_path(post) %>
    <% end %>

8. Create a way to get to the posts. In `config/routes.rb` add, `resources :posts`
9. In `app/views/posts/`, create a new file called `show.html.erb` and add the following code:

   

<%= @post.title %>


    <%= @post.body %>

10. Done. :)


## To create a blog post ##
1. Open Rails console by running `rails console`
2. Run `Post.create(title: "My Title", body: "This is my awesome blog post!")`


## To view the blog ##
1. Start the Rails server by running `rails server`
2. Navigate to `localhost:3000/posts`


~ Danial Goodwin ~



No comments: