Rails tutorial: Simple blog subscription feature in Rails

Before start this you have to setup new rails application with MySQL database. My previous post help you. Check this link:

Setting MySQL database to Rails Application

First of all generate a model called Subscriber with following command:

rails g model Subscriber email:string

Which will generate Subscriber model (app/model) directory and a migration file in db/migrations directory.

Then run following command

rake db:migrate

Note: rake is now moved to rails. so you can also run following command: rails db:migrate

Now we have to add validation to check for empty and correct email format of email field to our Subscriber model.

class Subscriber < ActiveRecord::Base
   validates :email, presence: true
   validates :email, uniqueness: true
   validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create

Now time to configure routes. We can configure routes in routes.rb as following.

Rails.application.routes.draw do
   resources :subscribers, only: [:create]

Which will generate following routes:

rake routes | grep subscribers
HTTP Verb Path         Controller#Action  Named Helper
POST      /subscribers subscribers#create subscribers_path

Now its time to create form partial which we can we use in any pages. For this create a partial file to app/views/shared/_subscription_form.html.erb . Which includes following codebase.

<div class="recent">
  <h3>Subscribe Blog</h3>
   <%= form_for :subscriber, url: subscribers_path do |f| %>
     <span><label for="email">Email</label></span>
     <%= f.text_field :email, class: 'form-control' %>
     <%= f.submit %>

Now we can render this partial file from any views as following:

<%= render 'shared/subscription_form' %>

At this situation we have model, routes and view for subscription form is ready. Not its time to write controller action to create subscriber record.

class SubscribersController < ApplicationController

  def create
    subscriber = Subscriber.new(subscriber_params)
    if subscriber.valid?
      flash[:success] = "You have subscribed successfully"
      flash[:error] = "Problem in subscription: #{subscriber.errors.full_messages.join(', ')}"
    redirect_to :back

  def subscriber_params

To display the proper error and success message put following line of codes in any suitable view files. Here you can use this on subscription_form partial.

<% [:success, :error].each do |key| %>
  <% if flash[key] %>
    <div class="<%= key %>" id="flash">
      <%= flash[key] %>
   <% end %>
<% end %>

Now its time to see result.

For Rails MVC please check following links from RailsGuide:

Feel free to add comment if you face any problem.


Leave a Reply

Your email address will not be published. Required fields are marked *