Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Rails Girls LA Guide

Rails Girls LA 2015 Part1

Our Goals

At the end of the day you should

  • Feel comfortable in the terminal
  • Know about ERB (Embeded Ruby) and how to use it
  • Know how to start a new Rails project
  • Have your project online
  • Know the difference between your local and remote code
  • Be comfortable in git
  • Know what MVC means
  • Learn some markdown
  • Have added a Gem to your project
  • Know about our friend Bundler
  • Meet new friends to learn with
  • Find a mentor
  • Get resources to continue learning
  • Have Fun! <3

Creating the Application

We’re going to create a new Rails app called la_adventures

Our App

L.A. Adventures

A bucket list for things to do in Los Angeles.
If you moved out of Los Angeles next month what are the places you wished you went to and the things you wish you did. Make a list of cool things to do so you can make a plan to do them in case you move someday. You don't want to have any regrets.

This is a long tutorial. You may want to browse through it quickly and decide together as a group which things are most important to you and be sure to do those things first.

Don't skip taking breaks and being away from the computer. Regular breaks allow you to go longer and learn more.

If you have any problems please let someone know. Code of Conduct

Share your sites at the end of the day:**


Coach: - take notes for your group in a gist on GitHub. Write what they tell you to and add some links as you go along through the day. Share the file with each other. Use markdown. You can discuss markdown later in the tutorial.


Kindness, Consideration and Respect.

  • Be kind to yourself. You are not less than anyone else because you don't know something.
  • Be considerate. Remember that all the coaches and organizers are happily volunteering their time to help you.
  • Respect others. Remember your coach is having patience with you so have patience with your student pair.

Let's Dive into Rails

First, let’s open a terminal:

  • Mac OS X: Open Spotlight, type Terminal and click the Terminal application.
  • Windows: Click Start and look for Command Prompt, then click Command Prompt with Ruby on Rails.
  • Linux (Ubuntu/Fedora): Search for Terminal on the dash and click Terminal.

Next, type these commands in the terminal:

mkdir railsgirls

You can verify that a directory named railsgirls was created by running the list command: ls.

You should see the railsgirls directory in the output.

Change into the railsgirls directory by running:

cd railsgirls

You can verify you are now in an empty directory or folder by again running the ls command.

Now you want to generate a new rails app called la_adventures by running:

rails new la_adventures

This will create a new app in the folder(directory) la_adventures.

Again, we want to change the directory to get inside of our rails app by running:

cd la_adventures

If you run ls inside of the la_adventures directory you should see folders such as app and config. Look at all the stuff you got from typing 3 small words. rails new la_adventures

The below chart is from the Railsbridge Intro to Rails tutorial

File/Folder Purpose
app/ Contains the controllers, models, and views for your application. You will do most of your work here.
config/ Configure your application's runtime rules, routes, database, and more.
db/ Shows your current database schema, as well as the database migrations.
public/ The only folder seen to the world as-is. If you put files in here, they will be served directly without any processing by Rails.
app/assets/ This is where your images, JavaScript, stylesheets (CSS), and other static files should go. Modern Rails apps use something called the Assets Pipeline, which combines all the JavaScript and CSS files in this directory into a single file for speediness.

Look at your New App

Start the rails server to see your new app by running:

rails server

Open http://localhost:3000 in your browser.
You should see “Welcome aboard” page, which means that the generation of your new app worked correctly.
You may want to run a second terminal to have the rails server run continuously.

You are now running a server.

The WEBrick server. This is so you can see what your app will look like in production on the web. Notice that each time you add a new adventure or do anything inyour web site the server in your terminal shows a bunch of new stuff. If you look at it you can see what it is doing relates to what you are doing on the site. You should see something like this below:

=> Booting WEBrick
=> Rails 4.2.0 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server

When you are running the Rails server you cannot execute new commands.
If you try running cd or another command it will not work.
To return to the normal command prompt:

Type CTRL-C in the terminal to quit the server.

Hooray for The Terminal Slide Show!

Go over the commandline prompts

  • pwd "print working directory" / it prints the path of our current directory, and by path, we mean the list of folders, or directories, we entered to get to where we are.
  • cd <directory_name> "change directory" / this allows us to enter a different folder depending on what we substitute into <directory_name>. If we enter a name, it will bring us into that folder if there is a direct link to it as in if that folder is contained within our current folder.
  • cd ../ brings us back one directory. From experience, I believe " cd .." alone would suffice.
  • mkdir <directory_name> "make directory" / creates a new directory for us
  • ls "list" / prints out all the files in our current directory
  • up and down arrow keys enters our previous commands
  • tab auto-completes file names
  • rm "remove" / deletes the file. "rmdir" removes a directory.
  • rails server or rails s starts our local server in our terminal
  • ctrl+c shuts down our server if its active
  • ctrl+l clears the terminal screen. "clear" itself also works, unless we're in the rails command-line.
  • man <command_name> "manual" / help screen for any command combined with this

Local Version Control with Git

Before we do anything else lets create a local repository and save our new project to it. We will use a workflow for git that follows along these lines each time we commit. Hooray for TryGit!

If you are working in a Virtual Box / Vagrant instance

You can open your new app in your terminal in two places

  1. you can open it in the vagrant instance: vagrant@vagrant-ubuntu-trusty-64:/vagrant/railsgirls/la_adventures
  2. and in your home directory wherever you put it. Mine is here: $Desktop/railsgirls/la_adventures

When you commit, do it from from outside of Vagrant #2. above

Create a git repository by typing.

$ git init

Do each of these commands one at a time...

git status
git add .
git status
git commit -m 'Initial commit'
git status

This chart shows what each command means. This is your git workflow. Which means EVERY TIME we ask you to commit to git and GitHub in this tutorial you should follow these steps. It is a good habit to follow all these steps.

Your Git Workflow :)
git status Check status
git add . Add everything to the repository
git status Check status
git commit -m 'Your comment' Commit everything (-m means message)
git status Check status*

Again I will say, every time you commit, follow these steps. It's good practice and it will help you from getting messed up when things get more complex.
Where it says Your comment this is where you write in what you commit contains. It should note what you did. These comments are meant for you to remember what you did so make them very meaningful.
They are also public for everyone to read for ever. ;) A Note About Git Commit Messages

Psst - If you ever see a $ sign, it is generally not part of the code. The $ sign usually means that you should type the code into your terminal. (unless you are using PHP. :)

Remote Version Control with GitHub

Pushing to GitHub :)
Create a Github repository
Add the remote host to your local git git remote add origin
Check your remotes git remote -v
Push commit to Github git push -u origin master

Coach: Discuss you git workflow.

For the rest of the project you will only need to use the command git push origin master to push your changes to GitHub.

Update the README

Change the name of this document and add your name.

$ git mv README.rdoc

Open the in your text editor. This is a markdown file that has a certain syntax like HTML. that why it's called The .md suffix is for markdown. This guide is written in markdown. :)

## Rails Girls 2015 


### L.A. Adventure App

*Made by* **Your Name**

Coach: Discuss markdown a little bit and other DSLs. Show how to create a gist in Github.

Run your git workflow again to commit this change.

Remember to commit from outside of your Virtualbox / Vagrant Instance Commit from your home directory wherever you put it. Mine is here: $Desktop/railsgirls/la_adventures

Do each of these commands one at a time...
git status
git add .
git status
git commit -m 'Initial commit'
git status
git push origin master

Each time you make a change you should commit it. Think, small commits.

Coach: Look at your commit on Github. Show how the comments in Github can be changed with markdown.

Create the Adventure scaffold

We’re going to use Rails’ scaffold functionality to generate a starting point that allows us to list, add, remove, edit, and view things.
In our case the scaffold and C.R.U.D. will let us: list adventures, add adventures, remove adventures and view adventures.

In Rails we call it C.R.U.D., the acronym for


We will be creating this in our database and you can imagine it looking a bit like this:

Adventure -
name string
description text
picture string
visit date
id (rails with provide an id automatically)
Before we create the model...

Let's just peek in app/model
Note that there is no model there yet.
After we run the next command there will be an Adventure model. app/models/adventure.rb
( You can also peek at app/controllers and app/views.)

Type this in your terminal to create your first scaffold

rails generate scaffold adventure name:string description:text picture:string visit:date

The scaffold creates new files in your project directory, but to get it to work properly we need to run a couple of other commands to update and create our Adventure database.


Coach - Talk a bit about Active Record. Active Record is the M in MVC - the model - which is the layer of the Rails responsible for logic. Active Record facilitates the use of your database.

Active Record uses some naming conventions.
Rails will pluralize your class names to find the respective database table.
So, for a class Book, you should have a database table called books. Therefore our class Adventure will have a database table called adventures.


Let's look at the file that will be run when we type in rake db:migrate.

Open the db/migrate/(date_time)_create_adventures.rb file. (Psst - (date_time) will be different in every app)

Notice that all the things that we just typed to create the scaffold are here in this file:

class CreateAdventures < ActiveRecord::Migration
  def change
    create_table :adventures do |t| 
      t.string :name
      t.text :description
      t.string :picture :visit
      t.timestamps null: false

Now you can run this command in your terminal. This will run the migration file


rake db:migrate
Restart your server and check out your app. (You have to restart your server when you run rake db:migrate)

Open http://localhost:3000/adventures in your browser.

rails server

Your new app might not look like much but it's awesome.

(For now your image will only be a string. We will make it an image later in the guide.)

Play around with your new app.

  • Create some new adventures.
  • Delete some.
  • List them all.
  • Create some more.
  • See what the C.R.U.D. is all about.


  • Rails scaffolding
  • The command rails generate scaffold adventure name:string description:text picture:string visit:date
  • MVC Model View Controller
  • The model name and related database table
  • Naming conventions
  • What are migrations and why do you need them?
  • What is Rake?

All of our adventures are stored in our database. This is where we get into the MVC or the Model View Controller aspect of our application.

How did all those pages get created and hooked together?

The Rails scaffold did it for you.

The following explanation is from the Railsbridge Intro to Rails tutorial

(Psst -You should try this tutorial on your own after this workshop. It is excellent! Sarah Mei and Sara Allen are responsible for creating Rails Bridge which inspired the creation of Rails Girls which is why you are here today. If you ever meet these women shake their hand vigorously and thank them.)
Also you should know the names Linda Liukas and Karri Saarinen who founded Rails Girls and are awesome! :)

Let's take a closer look at some of the files Rails created:


This file contains code for our adventure model. If you look at it, it's nearly blank. Creating, reading, updating, and deleting records are built into Rails.


This folder contains all the views for our adventures model. This is where the code for the forms you used above is stored. Rails created all of these pages as part of the scaffold. If you've written HTML before, many lines in the views should look familiar. Rails views are HTML with some extra code added to display data from the database. Yay Dash tutorial!


This is the code for the page that lists all the adventures. Index is the name given to the "default" page for a web site or a section of a web site. When you navigate to http://localhost:3000/adventures the adventures index page is what is sent to your computer.


This is the page you get when you click the "Show" link on the "Listing adventures" page.


This is the page you get when you click "New Adventure".


This is the page you get when you click "Edit".


You may have noticed that the page for new adventures and the page to edit adventures looked similar. That's because they both use the code from this file to show a form. This file is called a partial since it only contains code for part of a page. Partials always have filenames starting with an underscore character.

Challenge question: Can you find the line of code in new.html.erb and edit.html.erb that makes the form partial appear?


This is the controller file that Rails created as part of the scaffold If you look you'll see a method (a line beginning with def) for each of the views listed above (except _form.html.erb)


You may have noticed that the first page of your application still shows the “Welcome aboard” page. Let’s make it go straight to the Adventures page.

Open config/routes.rb and after the first line add

root 'adventures#index'

Test the change by opening the root path http://localhost:3000 in your browser.

Coach: Talk about routes, and include details on the order of routes and their relation to static files.

Deploy to Herouku

We are now going to put our app on the internet.
First you have to
Run your git workflow again to commit all changes.
Your message this time should be 'Add Adventure scaffold, Update routes to show Adventure on home page'

Because we are going to deploy our app to Heroku we need to update our Gemfile.
Why? Well, because we are using a Sqlite3 database and Heroku uses a Postgres database.
That's completely alright.
The Sqlite3 database easily transfers to the postgress data bases.
Luckily Rails has multiple environments Development, Production and Test.

  • The Development environment is where you develop your app.
  • The Production environment is what you "push to production" / Heroku or whatever server you use.
  • The Test environment is for testing.

Open your Gemfile. Find the sqlite3 gem:

gem 'sqlite3'

Add it to the development environment and declare the production environment to use postgress:
Notice it says group :development and group :production.
The do end means this is a block ask your coach what a block is.

Put this in your Gemfile:

group :development do
  gem 'sqlite3'
group :production do
  gem 'pg'

Then run this in your terminal:
(You must be in your Virtual Box / Vagrant Instance to run bundle.)

bundle install --without production to setup your dependencies.

Coach: - Discuss why you run bundle install and what the Gemfile.lock is doing.

If heroku is not running you may need to install the heroku toolbelt.

Adding rails_12factor

Next, we need to add rails_12factor entry into our Gemfile to make our app available on Heroku.

This gem modifies the way Rails works to suit Heroku, for example Logging is updated and the configuration for static assets (your images, stylesheets and javascript files) is tweaked to work properly within Heroku’s systems.

Please change the following in the Gemfile:

group :production do
  gem 'pg'


group :production do
  gem 'pg'
  gem 'rails_12factor'

Then run this in your terminal:


Run your git workflow again to commit all changes and push to Heroku.

Your comment should be 'Add rails_12factor gem and update Gemfile.lock'

Yes, you did just do this. Ugh, why wasn't it just combined with the last change to your Gemfile?
So you know that EVERY TIME you change your Gemfile you have to run $ bundle!

Deploying your App

App creation

Read this all first and discuss it and then we'll do these two commands.

In your terminal type:

heroku create

Then type:

git push heroku master

We need to create our Heroku app by typing heroku create in the terminal and see something like this:

Creating sheltered-refuge-6377... done, stack is cedar |
Git remote heroku added

In this case “sheltered-refuge-6377” is your app name.

Pushing the code

Next we need to push our code to heroku by typing git push heroku master. You’ll see push output like the following:

Initializing repository, done.
Counting objects: 101, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (91/91), done.
Writing objects: 100% (101/101), 22.68 KiB | 0 bytes/s, done.
Total 101 (delta 6), reused 0 (delta 0)

-----> Ruby app detected
-----> Compiling Ruby/Rails
-----> Using Ruby version: ruby-2.0.0
-----> Installing dependencies using 1.6.3
       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4    --deployment
       Fetching gem metadata from
-----> Launching... done, v6 deployed to Heroku

You’ll know the app is done being pushed, when you see the “Launching…” text like above.

Migrate database

Next we need to migrate our database like we did locally during the workshop:

** Run this command in your terminal:**

heroku run rake db:migrate

View Your App!

In a browser got to (except put the name of your app in there instead of sheltered-refuge-6377.)

You can also type heroku open in the terminal to visit the page.

Heroku’s platform is not without its quirks. Applications run on Heroku live within an ephermeral environment — this means that (except for information stored in your database) any files created by your application will disappear if it restarts which is why it takes so long to spin up when you first go to the site.

Obviously this doesn’t seem to be useful if you were running a real life application, but there are ways to work around this which is commonly used by a lot of popular websites.

Take a break. Stretch. Walk around the block. Notice that there are other people in the room.
Don't skip taking breaks and being away from the computer. Regular breaks allow you to go longer and learn more.

Proceed onward to Part 2 :)

Rails Girls LA 2015 Part2

I hope you are ready to roll again and make some more cool changes to your new site. This is where it really starts to look like something cool and you will start to see the potential of Rails.

Adding Photos

We need to install a piece of software to let us upload files in Rails.

Open the Gemfile in the project directory using your text editor.
In the main section (not in production or development) add the [carrierwave gem}(

gem 'carrierwave'

Coach: Explain what libraries (Gems) are and why they are useful. Describe what open source software is.

In the terminal run:


Now we can generate the code for handling uploads.

In the terminal run:

rails generate uploader Picture

Open app/models/adventure.rb and under the line

class Adventure < ActiveRecord::Base


mount_uploader :picture, PictureUploader

Open app/views/adventures/_form.html.erb and change

<%= f.text_field :picture %>


<%= f.file_field :picture %>

Sometimes, you might get a TypeError: can’t cast ActionDispatch::Http::UploadedFile to string. If this happens, in file app/views/adventures/_form.html.erb change the line

<%= form_for(@adventure) do |f| %>


<%= form_for @adventure, :html => {:multipart => true} do |f| %>

Add this line to your config/application.rb file

config.autoload_paths += %W(#{config.root}/app/uploaders)

In your local browser, add new adventure with a picture. When you upload a picture it doesn’t look nice because it only shows a path to the file, so let’s fix that.

Open app/views/adventures/show.html.erb and change

<%= @adventure.picture %>


<%= image_tag(@adventure.picture_url, :width => 600) if @adventure.picture.present? %>

Re-start your rails server now. (CTRL-C)


 rails server

Run your git workflow again to commit all changes.

Coach: Talk about Embedded Ruby. Show them what the embedded ruby looks like when you "Inspect Element" in the browser.

Mixed in with our HTML is Ruby code. How does the server know what to execute as Ruby and what to serve up as HTML? There are a few ways to do this, but for our project (and many Rails projects) we use <%= RUBY CODE HERE %> to tell the server when we're using Ruby code. The server executes this code as Ruby code and then embeds it in the existing HTML.

Design & Bootstrap

The app doesn’t look very nice yet. Let’s do something about that. We’ll use the Twitter Bootstrap project to give us nicer styling really easily.


  • Discuss what Boostrap is and does.
  • Talk a little about CSS and layouts.
  • Talk about the relationship between HTML and Rails. What part of views is HTML and what is Embedded Ruby (ERB)?
  • How does MVC relate to this? (Models and controllers are responsible for generating the HTML views.)
  • The 3 types of css styles. Inline, Internal, External.
Note that the pictures you uploaded before as strings will not be a photos now.

You have to download the photos to your computer so you can upload them with your app and push it.

Open app/views/layouts/application.html.erb in your text editor and above the line

 <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>


<link rel="stylesheet" href="//">
<link rel="stylesheet" href="//">

and replace

<%= yield %>


<div class="container">
  <%= yield %>

We are using an external stylesheet called <link rel="stylesheet" href="//">.
Check out what it looks like.

Let’s also add a navigation bar and footer to the layout. In the same file,
under <body> add

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      <a class="navbar-brand" href="/">The L.A. Adventure App</a>
    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="/adventures">Adventures</a></li>

and before </body> add

  <div class="container">
    Rails Girls 2015
<script src="//"></script>

**Let’s also change the styling of the adventures table. **

Open app/assets/stylesheets/application.css and at the bottom add

body { padding-top: 100px; }
footer { margin-top: 100px; }
table, td, th { vertical-align: middle; border: none; }
th { border-bottom: 1px solid #DDD; }

Save your files and refresh the browser to see what was changed.

Adjust the application layout

Open app/assets/stylesheets/application.css, replace the line

body { padding-top: 100px; }


body { padding-top: 60px; }

Delete the file app/assets/stylesheets/scaffolds.css.scss because we don’t really need the default style generated by Rails.

Now refresh the page at http://localhost:3000/. You will not find much change but it’s good preparation for the following steps.

Refine the navigation

Considering “adventure” is the most important object in your app,
we are going to put the “New Adventure” button on the navigation bar to make it always available.

Open app/views/layouts/application.html.erb, under the line

<li class="active"><a href="/adventures">Adventures</a></li>


<li ><%= link_to 'New Adventure', new_adventure_path %></li>

Design the Adventure list

It’s time to make the adventure list page look professional. For that, we are going to replace the table layout with a div layout.

Coach: Talk a little about table versus div.

Open app/views/adventures/index.html.erb in your text editor and replace all lines with
(Take the time to type it in.)

<h1>Listing Adventures</h1>

<% @adventures.in_groups_of(3) do |group| %>
  <div class="row">
    <% group.compact.each do |adventure| %>
      <div class="col-md-4">
        <%= image_tag adventure.picture_url, width: '100%' if adventure.picture.present?%>
        <h4><%= link_to, adventure %></h4>
        <%= adventure.description %>
    <% end %>
<% end %>

Coach: Explain what the new code means line by line, and talk a little about Bootstrap 12 grids layout.

Look at you web page now! We get a nice looking adventure list. Click the “New Adventure” button, and create more adventures with real text and pretty pictures - the page will look much better with content. There is a principle of contemporary web design: content is the best decoration.

Design the Adventure details page

Click the title of an adventure, and you will be brought to the details page of the adventure. Now it is still scaffold generated by Rails, so let’s make it better.

Open app/views/adventures/show.html.erb in your text editor and replace all lines with

<p id="notice"><%= notice %></p>

<div class="row">
  <div class="col-md-9">
    <%= image_tag(@adventure.picture_url, width: '100%') if @adventure.picture.present? %>

      <div class="col-md-3">
    <p><b>Name: </b><%= %></p>
    <p><b>Description: </b><%= @adventure.description %></p>
      <%= link_to 'Edit', edit_adventure_path(@adventure) %> |
      <%= link_to 'Destroy', @adventure, data: { confirm: 'Are you sure?' }, method: :delete %> |
      <%= link_to 'Back', adventures_path %>

Coach: Make a plan with your students. Time box how long you want to spend on styling. Stick to it. There is a lot more to learn.

Run your git workflow again to commit all changes.

Push to GitHub

Push to Heroku

Create an Info Page

Lets add a static page to our app that will hold information about the author of this application — you!

rails generate controller pages info

This command will create you a new folder under app/views called /pages and under that a file called info.html.erb which will be your info page.

It also adds a new simple route to your routes.rb.

get "pages/info"

Now you can open the file app/views/pages/info.html.erb and add information about you in HTML. To see your new info page, take your browser to http://localhost:3000/pages/info.

Test your App with RSpec

Install rspec

For starters, let’s install RSpec and all of its dependencies. In your Gemfile. group :test, :development do gem 'rspec-rails' end

Then in our terminal we want to bundle install bundle install

Now we want rspec to create it's /spec directory with a couple of files. In our terminal we run the command rails generate rspec:install

In our project directory. This creates spec_helper.rb, rails_helper.rb in the spec folder, and .rspec.

Rubyists often use the words ‘test’ and ‘specification’ interchangeably, that’s why you’ll store your tests in the ‘specs’ folder. Save your test as adventure_spec.rb (<name_of_spec>_spec.rb).

Coach: Create a models folders in the spec directory $ mkdir spec/models Coach: Show how to create a new file using $ touch spec/models/adventure_spec.rb

Create a new file called spec/models/adventure_spec.rb and add this to it.

require "rails_helper"

Next, let’s describe one of our specifications

describe Adventure do
  it "has a title" # your examples (tests) go here

Let's run the test. In your terminal run

bundle exec rspec spec/models/adventure_spec.rb

which will output that your test is pending as it’s not yet implemented.

Let’s do something about that! Change your test to:

describe Adventure do                # Given: I am on the adventure page
  it "has a title" do                
    adventure =        # When: A user creates a new adventure 'instance'
    adventure.title.should be_true   # Then: The new adventure has a title

Let's run the test again. In your terminal run

bundle exec rspec spec/models/adventure_spec.rb

Coach: Talk about googling terminal output (errors), the Rails Api, Stack Overflow. Talk about Given, When, Then. Make sure it is clear that the students understand commenting.


You could actually also write:

describe Adventure do
  its(:title) { should be_true }

which looks a lot nicer, but there’s a lot of magic involved. For now it’s probably just nice to know that we can ‘refactor’ those big chuncks of code into smaller bits with a little more experience.

Coach: Talk a bit about refactoring.

Allow People to Comment on the Adventures

Create a comment scaffold, with the commentator name, the comment body (contents of the comment) and with the reference to the adventures table (adventure_id).

In your terminal generate another scaffold.

rails g scaffold comment user_name:string body:text adventure_id:integer

This will create a migration file that lets your database know about the new comments table.

Run the migrations using

 rake db:migrate

Add relations to models

You need to make sure that Rails knows the relation between objects (adventures and comments). As one adventure can have many comments we need to make sure the adventure model knows that.

Open app/models/adventure.rb and after the row

class Adventure < ActiveRecord::Base


has_many :comments

The comment also has to know that it belongs to an adventure.

So open app/models/comment.rb and after

class Comment < ActiveRecord::Base

add the row

belongs_to :adventure

Render the comment form and existing comments

Open app/views/adventures/show.html.erb and after the image_tag

<%= image_tag(@adventure.picture_url, :width => 600) if @adventure.picture.present? %>


<% @comments.each do |comment| %>
    <strong><%= comment.user_name %></strong>
    <br />
    <p><%= comment.body %></p>
    <p><%= link_to 'Delete', comment_path(comment), method: :delete, data: { confirm: 'Are you sure?' } %></p>
<% end %>
<%= render 'comments/form' %>

In app/controllers/adventures_controller.rb add to show action after the row

@adventure = Adventure.find(params[:id])


@comments = @adventure.comments.all
@comment =

Open app/views/comments/_form.html.erb and after

<div class="field">
    <%= f.label :body %><br />
    <%= f.text_area :body %>

add the row

<%= f.hidden_field :adventure_id %>

next, remove

<div class="field">
  <%= f.label :adventure_id %><br>
  <%= f.number_field :adventure_id %>

That’s it. Now view an adventure you have inserted to your application and there you should see the form for inserting a comment as well as deleting older comments.

Add star rating

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.