2019-06-21
Today we will be building a simple Ruby on Rails application that allows you to store photos in Albums that you create. First things first, this article assumes you have basic knowledge of the Ruby language and that you are familiar with rails, follow along to get a nifty app to store your photos.
Written by: Joseph Reilly
rails new photo_app
rails g resource Album
rails g resource Photo
class Album < ApplicationRecord
has_many :photos
end
class Photo < ApplicationRecord
has_one :album
end
class CreateAlbums < ActiveRecord::Migration[5.2]
def change
create_table :albums do |t|
t.string :name
t.timestamps
end
end
end
class CreatePhotos < ActiveRecord::Migration[5.2]
def change
create_table :photos do |t|
t.string :name
t.string :image_url
t.references :album
t.timestamps
end
end
end
7.rails db:migrate
rails server
go to localhost:3000 in your browser and Yay we are on Rails!
rails db:migrate
rails server
Your schema.rb should look like this
create_table "albums", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "photos", force: :cascade do |t|
t.string "name"
t.string "image_url"
t.integer "album_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["album_id"], name: "index_photos_on_album_id"
end
Now we have to set up our views in order to get something other than an error or the generic rails welcome app.
In the views/albums folder that was created for us lets add an index.html.erb.
Set up a standard HTML file with an h1 tag that says “Welcome to PhotoAlbum”.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Albums</title>
</head>
<body>
<h1>Welcome to PhotoAlbums</h1>
</body>
</html>
class AlbumsController < ApplicationController
def index
end
end
navigate over to your first view page albums
High five yourself, you now have a working rails application.
If you have successfully gotten to this point of my tutorial then you are well on your way to creating a function photo album app. In the second part of this tutorial, I will show you how to create methods that will allow you to have a photos page where you can view all of your photos and set up the albums controller to allow for photos to be associated to the album you want to keep them in.