SlideShare a Scribd company logo
Building Web Apps with Rails

                           III
Recap
● Rails Console
●
  ActiveRecord Queries

●   Views
    ●
      Embedded Ruby Syntax
    ● Layouts

    ● Helper Methods
Recap: ActiveRecord




               Models             Controllers
 DB


       In stations_controller.rb (show):

@stations = Station.find(params[:id])
The Rails Console


1. Open the terminal
2. Navigate to the 'firstfm' directory
3. Run the commands:
   rails console
   @stations = Station.all
show.html.erb:


<%= link_to 'Edit', 
edit_station_path(@station) %> 
|
<%= link_to 'Back', stations_path %>




    These are both view helpers.
<!DOCTYPE html>
<html>
<head>
 <title>Firstfm</title>
 <%= stylesheet_link_tag "application" %>
 <%= javascript_include_tag "application"
%>
   <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>              The default layout
                              template.
</body>
</html>
Web Browser
Session 3



            Rails
                              Routing System


                             Views


                    Models
DB                                    Controllers
Web Browser
Session 3: Routing



           Rails
                             Routing System


                            Views


                   Models
DB                                   Controllers
Web Browser
Session 3:
Validations & Testing


           Rails
                             Routing System


                            Views


                   Models
DB                                   Controllers
Web Browser
Session 3:
Associations
& The 'Stream' Model

           Rails
                             Routing System


                            Views


                   Models
 DB                                  Controllers
Routing in Rails
Routing in Rails

                   ●
                       Which controller to
    Web Browser
                       instantiate

                   ●
                       Which action to invoke

                       Parameter(s) to pass
        ?
                   ●
Routing in Rails
     Web Browser



                        ●   Follows routing rules
                             defined in:
   Routing System
                        ●   config/routes.rb
  Views


          Controllers
Routing in Rails
Config/Routes.rb:

Firstfm::Application.routes.draw do
  resources :stations
  #comments
end

                    Generates RESTful routes
                    for the 'Station' resource
Routing in Rails
Config/Routes.rb:

Firstfm::Application.routes.draw do
  resources :stationsTransfer Principles:
     Representational State
  #comments
           Use HTTP methods explicitly
end
                     Be stateless
          Expose directory structure-like URIs
        Handle multiple formats e.g. XML, JSON
Routing in Rails
Config/Routes.rb:

Firstfm::Application.routes.draw do
  resources :stations
  #comments
end
                    This means we can accept
                    requests for all the CRUD
                             actions
Routing in Rails: Terminal Time!

1. Open the terminal
2. Navigate to the 'firstfm' directory
3. Run the commands:

 rake routes
Routing in Rails: Writing Rules
Config/Routes.rb:

   resources :stations
Routing in Rails: Writing Rules
Config/Routes.rb (rewritten):

get 'statations' => 'stations#index'
get 'statations/:id' => 'stations#show'
get 'statations/new' => 'stations#new'
post 'statations' => 'stations#create'
put 'statations/:id' => 'stations#update'
delete 'statations/:id' =>
'stations#destroy'
Routing in Rails: Writing Rules
Config/Routes.rb:

   resources :stations

Generates URL helpers for us e.g.

  stations_path
  station_path(:id)
  new_station_path
  Etc...
Routing in Rails: Task

1. Define a root controller and action

2. Add a new action

  2.1 Write a new method in the controller
  2.2 Write a view file for it
  2.3 Write a routing rule so we can access it


 For docs on routing: guides.rubyonrails.org/routing.html
Tests and Validations
We have a
problem...
Our app accepts
empty station data
Tests and Validations
Solution:

  Write validations to prevent erroneous data
Tests and Validations
But First!

  Let's write tests.
Tests and Validations


               Scaffolding has generated test
                         files for us
Tests and Validations: Unit Testing
In firstfm/test/unit/station_test.rb:


require 'test_helper'

class StationTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


         We write tests by writing out 'assertions'
Tests and Validations: Unit Testing

require 'test_helper'

class StationTest < ActiveSupport::TestCase
  test "the truth" do
     assert 10 > 9
  end
end




'assertions' evaluate whether an object is what we expect it to be
Tests and Validations: Unit Testing

Running test scripts

ruby -Itest <script_name>


e.g.

ruby -Itest test/unit/station_test.rb
Tests and Validations: Unit Testing

ruby -Itest test/unit/station_test.rb

Script report example:

pass: 1, fail: 1, error: 0
total: 2 tests with 2 assertions in 0.215168805
seconds
Tests and Validations: Unit Testing

test "shouldnt save without name" do
  station = Station.new
  station.url = “http://myradio.com”
  station.description = “A cool radio 
station”
  assert !station.save
end
Tests and Validations: Unit Testing

test "should save" do
  station = Station.new
  Station.name = “My Radio”
  station.url = “http://myradio.com”
  station.description = “A cool radio 
station”
  assert station.save
end
Tests and Validations: Task!

Write test cases for your validations

Consider more than just presence of data e.g.

●
    Name shouldn't be longer than x characters

●
    URL should start with 'http://'

●
    Description shouldn't be less than x characters
Tests and Validations: Validate
●
    We write validation code in the model

●
    Rails provides us with several built in validation methods

●
    For example: 'validates_presence_of'
Tests and Validations: Validate
 Example: Using validates_presence_of
 In models/station.rb:




class Station < ActiveRecord::Base

 validates_presence_of :name, :url,
:description

end
Tests and Validations: Task!
 Make your tests pass by implementing validations
 like below




class Station < ActiveRecord::Base

 validates_presence_of :name, :url,
:description

end
Associations in RoR
Adding 'Streams'
First FM




           Station
First FM




    Station   Stream
First FM




    Station   Has many   Streams
First FM


Let's generate the stream model


 rails generate model stream
   url:string name:string
Create the db table by running the migration script...

 rake db:migrate
First FM



Let's check out our new stream model


rails c

mystream = Stream.new
First FM




    Station   Stream
First FM




    Station   Has many   Streams
First FM


has_many :streams


     Station   Has many    Streams


                    belongs_to :station
First FM


Let's see if our models are associated


 rails c

 mystation = Station.first

 mystation.streams
First FM

           OH NOES!
  We need to add a secondary key.


rails generate migration
  AddStationIdToStreams
  station_id:integer
First FM

           OH YEA!
    We've got a secondary key!

rake db:migrate

rails c
mystation = Station.first

mystation.streams
First FM

            Build
   Build and save a new stream


stream = mystation.streams.build

More Related Content

RoR 101: Session 3