Part-1: Building a Single Page Application (SPA) with Angular and Rails

Raghavendra S
2 min readDec 15, 2024

This 6-part blog series takes you through building a single-page application (SPA) using Angular for the frontend and Ruby on Rails for the backend. By the end of this series, you’ll have a fully functional SPA and understand the integration of these two frameworks.

Setting Up the Rails Backend

We’ll start by creating the backend API using Ruby on Rails in API mode.

Step 1: Install Rails and Create a New Project

  1. Ensure you have Ruby and Rails installed:
ruby -v 
rails -v

2. Create a new Rails API-only application:

rails new blog_api --api
cd blog_api

The --api flag ensures the app is optimized for JSON responses.

Step 2: Configure the Database

Edit the config/database.yml file to match your database credentials. For simplicity, we’ll use SQLite in development.

Run the following commands to set up the database:

rails db:create
rails db:migrate

Step 3: Generate a Resource

Create a resource to manage articles:

rails generate scaffold Article title:string content:text
rails db:migrate

This generates the model, controller, and routes for Article.

Step 4: Configure JSON Serialization

  • Use Active Model Serializers for JSON formatting:
bundle add active_model_serializers
  • Generate a serializer:
rails generate serializer Article
  • Customize the ArticleSerializer (located in app/serializers/article_serializer.rb) to include necessary fields.

Step 5: Enable CORS

Allow the Angular frontend to communicate with the Rails backend:

  • Add the rack-cors gem:
bundle add rack-cors
  • Update config/initializers/cors.rb:
Rails.application.config.middleware.insert_before 0, Rack::Cors do   
allow do
origins '*' # Replace with specific origin in production resource '*', headers: :any, methods: %i[get post put patch delete options]
end
end

At this point, your Rails API is ready to handle requests from Angular. (Contd ..)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Raghavendra S
Raghavendra S

Written by Raghavendra S

Artificial enthusiast. Rubyist.

No responses yet

Write a response