Skip to content

Instantly share code, notes, and snippets.

@kelso
Last active March 29, 2023 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kelso/ca35790045696e8a84ba6cbbe5968c8a to your computer and use it in GitHub Desktop.
Save kelso/ca35790045696e8a84ba6cbbe5968c8a to your computer and use it in GitHub Desktop.
Active Record - sample project

Active Record - sample project

Step by step tutorial to create very simple Contacts listing.

1. Generate new project

Open Terminal and run:

mkdir ~/Code
cd ~/Code

rails new address_book -m https://bit.ly/rails-template-clean

We are using -m for loading custom rails template https://bit.ly/rails-template-clean, that includes setup for Bootstrap 5, Sass, and provide ready-to-use navbar and static pages Index & About.

Running rails new above will create folder address_book in the current directory, including all initial project files.

2. Open the project in VSCode

File > Open Folder... and choose ~/Code/address_book

Alternatively, run this command in Terminal:

open -a 'Visual Studio Code' ~/Code/address_book

You can close Terminal now. For following commands, we will use built-in Terminal panel in the Visual Studio Code.

3. Run rails server

  1. Show Visual Studio Code's Terminal panel panel with shortcut: Cmd+j
  2. Run rails server, keep it open & running
    rails s
    
  3. Open second terminal panel for later use. Keep this terminal available.

4. Generate model Contact

Create the following Active Record model Contact, for storing contacts data. Run this in Terminal panel:

rails g model Contact first_name:string last_name:string phone:string age:integer

This generates a migration for database. You need to migrate the database to apply changes - see next step.

5. Migrate the database

Apply changes from migrations (files in db/migrate/*) to the database:

rails db:migrate

Note: use rails db:rollback to undo last migration.

6. Let's create some data (manually)

Open rails console:

rails c

6.1. Create

Run this Ruby code to create 2 contacts:

Contact.create(first_name: 'Bob', last_name: 'Doe', phone: '0901 123 123', age: 25)
Contact.create(first_name: 'Jan', last_name: 'Nocak', phone: '0901 456 456', age: 30)

You can check that 2 contacts were created:

Contact.count
# => 2

Alternatively you can create record like this:

contact = Contact.new first_name: 'Bob', last_name: 'Doe', age: 30
contact.save

Or:

contact = Contact.new
contact.first_name = 'Bob'
contact.last_name = 'Doe'
contact.age = 30
contact.save

Let's see other operations that are available below.

6.1. Retrieve records

Get record by ID:

contact = Contact.find(1)

Get record by other attribute:

contact = Contact.find_by(first_name: 'Doe')

Get first/last record:

Contact.first
# or
Contact.last

Notice that find, find_by, first, last return one instance of Contact.

But following methods return a collection ([Contact, Contact, ...])

Get all records:

contacts = Contact.all

Get records where last_name is Doe:

contacts = Contact.where(last_name: 'Doe')

Get records where age > 21:

contacts = Contact.where('age > ?', 21)

Sort records by age:

contacts = Contact.order(:age)

Sort records by age DESC:

contacts = Contact.order(age: :desc)

6.2. Update operation

Find & update contact:

contact = Contact.find_by last_name: 'Nocak'
contact.last_name = 'Novak'
contact.save

Alternatively, update:

contact = Contact.find_by last_name: 'Nocak'
contact.update last_name: 'Novak'

Alternatively, update in one line:

Contact.find_by(last_name: 'Nocak').update(last_name: 'Novak')

6.3. Delete operation

In case of one instance of Contact

contact.destroy

In case of collection:

contacts.destroy_all

6.4. Exit rails console

Exit rails console with command:

exit

6.5. More info

See official documentation: https://guides.rubyonrails.org/active_record_basics.html#crud-reading-and-writing-data

7. Generate controller and actions

rails g controller contacts index show

8. Modify config/routes.rb

Replace these lines:

get 'contact/index', to: 'contacts#index'
get 'contact/show', to: 'contacts#show'

with:

resources :contacts, only: %i[index show]

9. Modify controller

app/controllers/contacts_controller.rb:

class ContactsController < ApplicationController
  def index
    @contacts = Contact.all
  end

  def show
    @contact = Contact.find params[:id]
  end
end

10. Modify views

app/views/contacts/index.html:

<h1>Contacts</h1>

<p>
  Count: <%= @contacts.count %>
</p>

<% @contacts.each do |contact| %>
  <h2>
    <%= contact.first_name %>
    <%= contact.last_name %>
  </h2>

  <p>
    Phone: <%= contact.phone %><br>
    Age: <%= contact.age %>
  </p>
<% end %>

app/views/contacts/show.html.erb:

<h1>Contact detail</h1>
<h2>
  <%= @contact.first_name %> <%= @contact.last_name %>
</h2>
<p>
  Phone: <%= @contact.phone %><br>
  Age: <%= @contact.age %>
</p>

11. Open the web in browser

http://localhost:3000/contacts

Author

Štefan Húska

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment