This is article #6 in the Ruby for AI series, where we build practical Ruby skills step by step toward AI-powered applications.
Why Rails for AI Builders
Ruby on Rails gives you a complete web framework in minutes, not hours. For AI projects, you need a solid foundation: data storage, APIs, background jobs, and a user interface. Rails delivers all of this with convention over configuration, letting you focus on AI features instead of boilerplate.
This guide walks you through your first Rails application. You will understand Models, Views, and Controllers, then see how this structure supports AI integration later.
Installing Rails and Creating Your App
First, ensure you have Ruby installed (3.1 or newer recommended). Then install Rails:
gem install rails
Create a new Rails application for tracking AI training experiments:
rails new ai_lab --database=postgresql
cd ai_lab
Rails generates a complete project structure. The --database=postgresql flag prepares you for production workloads where AI data grows large.
Start the server to confirm everything works:
bin/rails server
Visit http://localhost:3000 and you will see the Rails welcome page.
Understanding MVC Architecture
Rails organizes code into three layers:
Models handle data and business logic. They talk to your database and validate information.
Views render what users see. They are templates that display data.
Controllers receive requests, use models to fetch data, and pass that data to views.
This separation keeps code maintainable. When you add AI features, models will hold prediction logic, controllers will handle API requests, and views will display results.
Generating Your First Resource with Scaffold
Rails scaffolding creates a complete MVC stack with one command. Let us build a system to track machine learning models:
bin/rails generate scaffold ModelRun name:string algorithm:string accuracy:float training_duration:integer parameters:jsonb
This generates:
- A database migration for the
model_runstable - A
ModelRunmodel with validations - A
ModelRunsControllerwith CRUD actions - View templates for listing, showing, creating, and editing records
- Routes connecting URLs to controller actions
Run the migration to create the database table:
bin/rails db:create
bin/rails db:migrate
Visit http://localhost:3000/model_runs and you have a working application. Create a few records to experiment.
Examining the Generated Code
Open app/models/model_run.rb:
class ModelRun < ApplicationRecord
end
The model inherits from ApplicationRecord, giving it database persistence. Add validations to ensure data quality:
class ModelRun < ApplicationRecord
validates :name, presence: true
validates :accuracy, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 1 }
validates :algorithm, inclusion: { in: %w[random_forest neural_network svm gradient_boosting] }
end
Check the controller in app/controllers/model_runs_controller.rb. The index action fetches records:
def index
@model_runs = ModelRun.all
end
The @model_run instance variable becomes available in the view. Open app/views/model_runs/index.html.erb to see how Rails renders the list.
Understanding Routes
Routes map URLs to controller actions. Open config/routes.rb:
Rails.application.routes.draw do
resources :model_runs
root "model_runs#index"
end
The resources line creates seven standard routes for CRUD operations. Run bin/rails routes to see them:
model_runs GET /model_runs(.:format) model_runs#index
POST /model_runs(.:format) model_runs#create
new_model_run GET /model_runs/new(.:format) model_runs#new
edit_model_run GET /model_runs/:id/edit(.:format) model_runs#edit
model_run GET /model_runs/:id(.:format) model_runs#show
PATCH /model_runs/:id(.:format) model_runs#update
PUT /model_runs/:id(.:format) model_runs#update
DELETE /model_runs/:id(.:format) model_runs#destroy
Later, you will add API routes for receiving predictions from external AI services.
Preparing for AI Integration
Your simple Rails app already supports AI workflows. Here is how each piece extends:
Models will integrate with Ruby machine learning libraries. Add a method to ModelRun that calls a prediction service:
class ModelRun < ApplicationRecord
def predict(features)
# This will connect to your AI service in later articles
PredictionService.new(self).predict(features)
end
end
Controllers will handle asynchronous AI processing. The create action can enqueue background jobs for training:
def create
@model_run = ModelRun.new(model_run_params)
if @model_run.save
ModelTrainingJob.perform_later(@model_run)
redirect_to @model_run, notice: "Training started"
else
render :new, status: :unprocessable_entity
end
end
Views will display AI outputs. Add a prediction form to show.html.erb:
<%= form_with url: predict_model_run_path(@model_run), method: :post do |f| %>
<%= f.label :features, "Input features (JSON)" %>
<%= f.text_area :features %>
<%= f.submit "Get Prediction" %>
<% end %>
<% if @prediction %>
<p>Result: <%= @prediction %></p>
<% end %>
Adding a Custom Route and Action
Let us implement that prediction endpoint. Add to config/routes.rb:
resources :model_runs do
member do
post :predict
end
end
Add the action to app/controllers/model_runs_controller.rb:
def predict
@model_run = ModelRun.find(params[:id])
features = JSON.parse(params[:features])
# Placeholder for AI integration
@prediction = { status: "pending", message: "AI service connection coming in article #8" }
render :show
rescue JSON::ParserError
redirect_to @model_run, alert: "Invalid JSON format"
end
Next Steps in the Series
You now have a functioning Rails application with database persistence, CRUD operations, and a foundation for AI features. The MVC structure keeps your code organized as complexity grows.
In article #7, we will add background job processing with Solid Queue to handle long-running AI training tasks. Article #8 connects your Rails app to external AI APIs. Article #9 brings in vector search with pgvector for similarity matching.
Master these fundamentals now. Every AI application needs reliable data management, clean APIs, and maintainable code. Rails gives you all three with minimal friction.
Top comments (0)