Building a Blog with Ruby on Rails

Building a Blog with Ruby on Rails

  • 2016-09-09
  • 1121

Introduction:

Ruby on Rails is an awesome framework for quickly and easily setting up a web application. In this tutorial I will show you how to build a blog platform using Ruby on Rails, we will make use of the gem ckeditor which is an integration gem for Ckeditor.

This will be a two part tutorial. In this post, we will focus on ensuring that posts can be created, edited, destroyed and viewed on the index and show page. In the part 2 we will integrate authentication so that only admins will be able to create posts. For the first part we want to be able to create a post using ckeditor, therefore our new post page will look like this:

enter image description here

Your post should be beautifully formatted to suit your options, like this:

enter image description here

By the end of this tutorial you will know how to create a basic CRUD application with Ruby on Rails, and also make use of Devise for authentication.

Rails Application

Using your terminal navigate to your working directory and generate your new rails application. I am calling mine scotch-blog.

    rails new scotch-blog -T

This will generate for you a new Rails application and install a couple of gems for you. The -T flag tells Rails to generate the new application without a test suite. When you generate a new Rails application, by default some gems are added for you to work with. Gems are like plugins or libraries with some functionality, installed to satisfy specific needs. There is almost a gem for everything you may want to do. Later on, I’ll write an article that explains what gems are.

Now we generate our Post model. Before doing that let us understand how the Post will work. For every created Post we want to be able to add a title and body of text. This should be saved to the database whenever the Submit button is clicked. Thus we need a posts table with title and body columns. That should do for a basic blog system.

Open your terminal and let’s generate our model:

    rails g model Post title:string body:text

That command created some files in our application. One of the files created is a migration file, you can see that in the directory; db/migrate. Now we need to migrate our database.

Run the command:

    rake db:migrate

And that should do the magic.

Installing Simple Form and Bootstrap-Sass

Before we move forward, let’s install simple_form and bootstrap-sass. Go to your Gemfile and paste in the following lines:

    #Gemfile

    gem 'simple_form', '~> 3.2'
    gem 'bootstrap-sass', '~> 3.3'

From your terminal run bundle install.

Now let’s set up bootstrap-sass. Move to app/assets/javascripts/application.js and add the line below:

    #app/assets/javascripts/application.js

    //= require bootstrap-sprockets

Just below the line that requires jquery.

Rename app/assets/stylesheets/application.css to app/assets/stylesheets/application.scss to create our Sass file. Paste in the following and save:

    #app/assets/stylesheets/application.scss

    @import "bootstrap-sprockets";
    @import "bootstrap";

Let us generate simple_form, we do so by running the command below:

    rails generate simple_form:install --bootstrap

This will generate some files and directories for us to make simple_form work.

Setting up the Posts Controller and Views

Let’s create our PostsController before moving on to our model.

    rails g controller Posts

That will generate some files and directories for our Post controller, but more on that later. For now let us set up our controller for creating a post.

Copy and paste the code below into app/controllers/posts_controller.rb:

    #app/controllers/posts_controller.rb

    class PostsController < ApplicationController
      before_action :find_post, only: [:edit, :update, :show, :delete]

      # Index action to render all posts
      def index
        @posts = Post.all
      end

      # New action for creating post
      def new
        @post = Post.new
      end

      # Create action saves the post into database
      def create
        @post = Post.new
        if @post.save(post_params)
          flash[:notice] = "Successfully created post!"
          redirect_to post_path(@post)
        else
          flash[:alert] = "Error creating new post!"
          render :new
        end
      end

      # Edit action retrives the post and renders the edit page
      def edit
      end

      # Update action updates the post with the new information
      def update
        if @post.update_attributes(post_params)
          flash[:notice] = "Successfully updated post!"
          redirect_to post_path(@posts)
        else
          flash[:alert] = "Error updating post!"
          render :edit
        end
      end

      # The show action renders the individual post after retrieving the the id
      def show
      end

      # The destroy action removes the post permanently from the database
      def destroy
        if @post.destroy
          flash[:notice] = "Successfully deleted post!"
          redirect_to posts_path
        else
          flash[:alert] = "Error updating post!"
        end
      end

      private

      def post_params
        params.require(:post).permit(:title, :body)
      end

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

Now we have our actions all geared up for the creation of new posts, but that is not all we need to do. We still need our views. Let’s handle that now.

Creating our Views

Go ahead and create the following files in app/views/posts directory:

  • index.html.erb
  • edit.html.erb
  • new.html.erb
  • show.html.erb
  • _form.html.erb

We need a form that will be rendered whenever a post is to be created. We will create a partial so that we can share the form across the new and edit pages.

A partial allows us to reuse our layouts across multiple pages. It starts with the underscore _ symbol. Here is the form partial we will be using.

    #app/views/posts/_form.html.erb

    <%= simple_form_for @post do |f| %>
      <% if @post.errors.any? %>
        <div id="error_explanation">
          <h2>
            <%= "#{pluralize(@post.errors.count, "error")} prohibited this post from being saved:" %>
          </h2>
          <ul>
            <% @post.errors.full_messages.each do |msg| %>
              <li>
                <%= msg %>
              </li>
              <% end %>
          </ul>
        </div>
      <% end %>

      <div class="form-group">
        <%= f.input :title, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.input :body, :as => :ckeditor, input_html: {:ckeditor => {:toolbar => 'FULL'}}, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.button :submit %>
      </div>
    <% end %>

With that done we can just render the form in our new and edit pages as I stated earlier. This is how you do it for new.html.erb

View for New Post

    #app/views/posts/new.html.erb

    <h2>Create New Post</h2>

    <%= render "posts/form" %>

View for Editing a Post

And edit.html.erb

    #app/views/posts/edit.html.erb
    <h2>Edit Post</h2>

    <%= render "posts/form" %>

View for Index

Let’s set up our index page:

    #app/views/posts/index.html.erb

    <div class="container">
      <div class="col-sm-10 col-sm-offset-1 col-xs-12 blog-content">
        <% @posts.each do |post| %>
        <div class="col-xs-12">
          <div class="text-center">
            <h2><%= post.title %></h2>
            <h6><%= post.created_at.strftime('%b %d, %Y') %></h6>
          </div>

          <div>
            <%= raw (post.body).truncate(358) %>
          </div>

          <div class="text-center">
            <%= link_to "READ MORE", post_path(post) %>
          </div>
          <br>
        </div>
        <% end %>
      </div>
    </div>

View for Displaying Posts

And our show page:

    #app/views/posts/show.html.erb

    <div class="col-sm-11 col-xs-12 blog-content">
      <h2 class="text-center"><%= @post.title %></h2>
      <h5 class="text-center"><%= @post.created_at.strftime('%b %d, %Y') %></h5>
      <div><%= raw @post.body %></div>
    </div>

Now we have created the necessary view files for creating, editing and viewing a posts, but there’s still more to do. For a post to be created we need to set up our routes.

From your text editor navigate to config/routes.rb and paste in the following codes:

    #config/routes.rb

    Rails.application.routes.draw do
      root to: "posts#index"

      resources :posts
    end

Can you guess what we are doing above?

We set the root of our application as posts/index, so whenever a visitor points her browser to the root of our application, she will be presented with the index page of our post.

The resources line provides us with all of the actions available, and the include: new, index, create, show, edit, update and destroy.

Installing CKeditor

Next let’s install ckeditor and use its editor for the creation and updating of a post, as it is a better option compared to what we already have.

First let us install the gem, open up your Gemfile and paste in the line below and save.

    #Gemfile

    gem 'ckeditor', '~> 4.1',

Go to your terminal and install:

    bundle install

In future we will enable image uploading in our blog, but let us go ahead and generate the necessary files for ckeditor to work with. Run the command below from your terminal:

    rails generate ckeditor:install --orm=active_record --backend=carrierwave

This will create some directories and files. You can go ahead and check them out according to the output shown on your terminal.

Now migrate your database.

    rake db:migrate

We need to load ckeditor, go to app/assets/javascripts/application.js and the line below just above the tree line.

    #app/assets/javascripts/application.js

    ...
    //= require ckeditor/init
    ...

Create a directory called ckeditor in app/assets/javascripts, then create a new file called config.js in the directory you just created. Paste in the code below:

    CKEDITOR.editorConfig = function(config) {
      config.language = 'en';
      config.width = '700';
      config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
      config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
      config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
      config.filebrowserImageUploadUrl = "/ckeditor/pictures";
      config.filebrowserUploadUrl = "/ckeditor/attachment_files";

      config.toolbar_Pure = [
        '/', {
          name: 'basicstyles',
          items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']
        }, {
          name: 'paragraph',
          items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl']
        }, {
          name: 'links',
          items: ['Link', 'Unlink']
        }, '/', {
          name: 'styles',
          items: ['Styles', 'Format', 'Font', 'FontSize']
        }, {
          name: 'colors',
          items: ['TextColor', 'BGColor']
        }, {
          name: 'insert',
          items: ['Image', 'Table', 'HorizontalRule', 'PageBreak']
        }
      ];
      config.toolbar = 'Pure';
      return true;
    };

Start up your rails server:

    rails server

Open your browser and navigate to http://localhost:3000/posts/new to see your new blog.

Conclusion

At this point we have been able to create a working blog with a super cool editor. In the next part of this tutorial we will tie authentication around it so only the admin can create post. I hope you enjoyed yourself.

The source code for the blog created can be found on [Github]

Suggest

Ruby Programming for Beginners

Ruby on Rails for Complete Beginners

Beginners Ruby Programming Training - No Experience Required

The Professional Ruby on Rails Developer

Make Medium (medium.com) Clone in Ruby on Rails