Build a CRUD Web App with Ruby on Rails

If you are fairly new to Ruby on Rails (or forgot how to use it) and need a quick guide to creating a CRUD (create, read, update, destroy) web application, then you’ve come to the right place!

Below I have written some simple steps to creating a very simple application, linked to some documentation or a tutorial for each step, and included an example of what you might write for each step.

Here’s a nice, simple tutorial that gives some more context and explanation and walks you through these steps. This guide is also fairly easy to follow, much longer, and more detailed.

  1. Create a new app
rails new pets-app

  1. Launch a server and go to http://localhost:3000 in your browser to view your app
rails s

  1. Create models
rails g model owner first_name last_name age:integer email
rails g model pet name species owner_id:integer owner:belongs_to

  1. Set up associations
class Owner < ApplicationRecord
  has_many :pets
end

  1. Add validations
class Owner < ApplicationRecord
  has_many :pets
  validates :name, presence: true
end

  1. Run migrations
rails db:migrate

  1. Check your schema by looking at the db/schema.rb file

  2. Seed your database

Owner.create!(first_name:"Dan", last_name:"Weirdo", age: 18, email:"realemail@cool.com")
Pet.create!(name:"Snowball", species:"dog", owner_id:1)

  1. Test associations
Owner.first.pets
Pet.first.owner

  1. Test validations
owner = Owner.new(first_name: "")
owner.valid?
owner.errors.messages

  1. Create controllers and views
rails g controller owners index show new create edit update destroy
rails g controller pets index show new create edit update destroy

  1. Create routes using resources or manual routes
resources :pets
resources :owners

  1. Make sure your routes are working correctly by running your server

(rails s) and looking at each path that you created (i.e. /pets)

  1. Add/edit controller actions

Hint: scroll to the bottom for an example of standard controller actions

  1. Add/edit view files

Hint: “find on page” “new.html”, “index.html”, etc. to see examples

Another hint: the form_for helper

That’s it! Make sure you test your code as you go, and commit often.

#ruby-on-rails #web-development

Build a CRUD Web App with Ruby on Rails
81.45 GEEK