0
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 = Sta...
The Rails Console1. Open the terminal2. Navigate to the firstfm directory3. Run the commands:   rails console   @stations ...
show.html.erb:<%= link_to Edit, edit_station_path(@station) %> |<%= link_to Back, stations_path %>    These are both view ...
<!DOCTYPE html><html><head> <title>Firstfm</title> <%= stylesheet_link_tag "application" %> <%= javascript_include_tag "ap...
Web BrowserSession 3            Rails                              Routing System                             Views       ...
Web BrowserSession 3: Routing           Rails                             Routing System                            Views ...
Web BrowserSession 3:Validations & Testing           Rails                             Routing System                     ...
Web BrowserSession 3:Associations& The Stream Model           Rails                             Routing System            ...
Routing in Rails
Routing in Rails                   ●                       Which controller to    Web Browser                       instan...
Routing in Rails     Web Browser                        ●   Follows routing rules                             defined in: ...
Routing in RailsConfig/Routes.rb:Firstfm::Application.routes.draw do  resources :stations  #commentsend                   ...
Routing in RailsConfig/Routes.rb:Firstfm::Application.routes.draw do  resources :stationsTransfer Principles:     Represen...
Routing in RailsConfig/Routes.rb:Firstfm::Application.routes.draw do  resources :stations  #commentsend                   ...
Routing in Rails: Terminal Time!1. Open the terminal2. Navigate to the firstfm directory3. Run the commands: rake routes
Routing in Rails: Writing RulesConfig/Routes.rb:   resources :stations
Routing in Rails: Writing RulesConfig/Routes.rb (rewritten):get statations => stations#indexget statations/:id => stations...
Routing in Rails: Writing RulesConfig/Routes.rb:   resources :stationsGenerates URL helpers for us e.g.  stations_path  st...
Routing in Rails: Task1. Define a root controller and action2. Add a new action  2.1 Write a new method in the controller ...
Tests and Validations
We have aproblem...
Our app acceptsempty station data
Tests and ValidationsSolution:  Write validations to prevent erroneous data
Tests and ValidationsBut First!  Lets write tests.
Tests and Validations               Scaffolding has generated test                         files for us
Tests and Validations: Unit TestingIn firstfm/test/unit/station_test.rb:require test_helperclass StationTest < ActiveSuppo...
Tests and Validations: Unit Testingrequire test_helperclass StationTest < ActiveSupport::TestCase  test "the truth" do    ...
Tests and Validations: Unit TestingRunning test scriptsruby -Itest <script_name>e.g.ruby -Itest test/unit/station_test.rb
Tests and Validations: Unit Testingruby -Itest test/unit/station_test.rbScript report example:pass: 1, fail: 1, error: 0to...
Tests and Validations: Unit Testingtest "shouldnt save without name" do  station = Station.new  station.url = “http://myra...
Tests and Validations: Unit Testingtest "should save" do  station = Station.new  Station.name = “My Radio”  station.url = ...
Tests and Validations: Task!Write test cases for your validationsConsider more than just presence of data e.g.●    Name sh...
Tests and Validations: Validate●    We write validation code in the model●    Rails provides us with several built in vali...
Tests and Validations: Validate Example: Using validates_presence_of In models/station.rb:class Station < ActiveRecord::Ba...
Tests and Validations: Task! Make your tests pass by implementing validations like belowclass Station < ActiveRecord::Base...
Associations in RoRAdding Streams
First FM           Station
First FM    Station   Stream
First FM    Station   Has many   Streams
First FMLets generate the stream model rails generate model stream   url:string name:stringCreate the db table by running ...
First FMLets check out our new stream modelrails cmystream = Stream.new
First FM    Station   Stream
First FM    Station   Has many   Streams
First FMhas_many :streams     Station   Has many    Streams                    belongs_to :station
First FMLets 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:in...
First FM           OH YEA!    Weve got a secondary key!rake db:migraterails cmystation = Station.firstmystation.streams
First FM            Build   Build and save a new streamstream = mystation.streams.build
Upcoming SlideShare
Loading in...5
×

RoR 101: Session 3

703

Published on

Part 3 of 6

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
703
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
15
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "RoR 101: Session 3"

  1. 1. Building Web Apps with Rails III
  2. 2. Recap● Rails Console● ActiveRecord Queries● Views ● Embedded Ruby Syntax ● Layouts ● Helper Methods
  3. 3. Recap: ActiveRecord Models Controllers DB In stations_controller.rb (show):@stations = Station.find(params[:id])
  4. 4. The Rails Console1. Open the terminal2. Navigate to the firstfm directory3. Run the commands: rails console @stations = Station.all
  5. 5. show.html.erb:<%= link_to Edit, edit_station_path(@station) %> |<%= link_to Back, stations_path %> These are both view helpers.
  6. 6. <!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>
  7. 7. Web BrowserSession 3 Rails Routing System Views ModelsDB Controllers
  8. 8. Web BrowserSession 3: Routing Rails Routing System Views ModelsDB Controllers
  9. 9. Web BrowserSession 3:Validations & Testing Rails Routing System Views ModelsDB Controllers
  10. 10. Web BrowserSession 3:Associations& The Stream Model Rails Routing System Views Models DB Controllers
  11. 11. Routing in Rails
  12. 12. Routing in Rails ● Which controller to Web Browser instantiate ● Which action to invoke Parameter(s) to pass ? ●
  13. 13. Routing in Rails Web Browser ● Follows routing rules defined in: Routing System ● config/routes.rb Views Controllers
  14. 14. Routing in RailsConfig/Routes.rb:Firstfm::Application.routes.draw do resources :stations #commentsend Generates RESTful routes for the Station resource
  15. 15. Routing in RailsConfig/Routes.rb:Firstfm::Application.routes.draw do resources :stationsTransfer Principles: Representational State #comments Use HTTP methods explicitlyend Be stateless Expose directory structure-like URIs Handle multiple formats e.g. XML, JSON
  16. 16. Routing in RailsConfig/Routes.rb:Firstfm::Application.routes.draw do resources :stations #commentsend This means we can accept requests for all the CRUD actions
  17. 17. Routing in Rails: Terminal Time!1. Open the terminal2. Navigate to the firstfm directory3. Run the commands: rake routes
  18. 18. Routing in Rails: Writing RulesConfig/Routes.rb: resources :stations
  19. 19. Routing in Rails: Writing RulesConfig/Routes.rb (rewritten):get statations => stations#indexget statations/:id => stations#showget statations/new => stations#newpost statations => stations#createput statations/:id => stations#updatedelete statations/:id =>stations#destroy
  20. 20. Routing in Rails: Writing RulesConfig/Routes.rb: resources :stationsGenerates URL helpers for us e.g. stations_path station_path(:id) new_station_path Etc...
  21. 21. Routing in Rails: Task1. Define a root controller and action2. 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
  22. 22. Tests and Validations
  23. 23. We have aproblem...
  24. 24. Our app acceptsempty station data
  25. 25. Tests and ValidationsSolution: Write validations to prevent erroneous data
  26. 26. Tests and ValidationsBut First! Lets write tests.
  27. 27. Tests and Validations Scaffolding has generated test files for us
  28. 28. Tests and Validations: Unit TestingIn firstfm/test/unit/station_test.rb:require test_helperclass StationTest < ActiveSupport::TestCase  # test "the truth" do  #   assert true  # endend We write tests by writing out assertions
  29. 29. Tests and Validations: Unit Testingrequire test_helperclass StationTest < ActiveSupport::TestCase  test "the truth" do     assert 10 > 9  endendassertions evaluate whether an object is what we expect it to be
  30. 30. Tests and Validations: Unit TestingRunning test scriptsruby -Itest <script_name>e.g.ruby -Itest test/unit/station_test.rb
  31. 31. Tests and Validations: Unit Testingruby -Itest test/unit/station_test.rbScript report example:pass: 1, fail: 1, error: 0total: 2 tests with 2 assertions in 0.215168805seconds
  32. 32. Tests and Validations: Unit Testingtest "shouldnt save without name" do station = Station.new station.url = “http://myradio.com” station.description = “A cool radio station” assert !station.saveend
  33. 33. Tests and Validations: Unit Testingtest "should save" do station = Station.new Station.name = “My Radio” station.url = “http://myradio.com” station.description = “A cool radio station” assert station.saveend
  34. 34. Tests and Validations: Task!Write test cases for your validationsConsider more than just presence of data e.g.● Name shouldnt be longer than x characters● URL should start with http://● Description shouldnt be less than x characters
  35. 35. 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
  36. 36. Tests and Validations: Validate Example: Using validates_presence_of In models/station.rb:class Station < ActiveRecord::Base validates_presence_of :name, :url,:descriptionend
  37. 37. Tests and Validations: Task! Make your tests pass by implementing validations like belowclass Station < ActiveRecord::Base validates_presence_of :name, :url,:descriptionend
  38. 38. Associations in RoRAdding Streams
  39. 39. First FM Station
  40. 40. First FM Station Stream
  41. 41. First FM Station Has many Streams
  42. 42. First FMLets generate the stream model rails generate model stream url:string name:stringCreate the db table by running the migration script... rake db:migrate
  43. 43. First FMLets check out our new stream modelrails cmystream = Stream.new
  44. 44. First FM Station Stream
  45. 45. First FM Station Has many Streams
  46. 46. First FMhas_many :streams Station Has many Streams belongs_to :station
  47. 47. First FMLets see if our models are associated rails c mystation = Station.first mystation.streams
  48. 48. First FM OH NOES! We need to add a secondary key.rails generate migration AddStationIdToStreams station_id:integer
  49. 49. First FM OH YEA! Weve got a secondary key!rake db:migraterails cmystation = Station.firstmystation.streams
  50. 50. First FM Build Build and save a new streamstream = mystation.streams.build
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×