SlideShare uma empresa Scribd logo
1 de 44
Rails at a Snail’s Pace



        Matt Reider

      Jen-Mei Wu
9:00 - 10:30 UNIT 1
                               Agenda    2.3 Questions
  1.1 Demo an app                       12:00 LUNCH
  1.2 What is Rails?                    1:00 - 1:45 UNIT 3
  1.3 Intro Environment                  3.1 ActiveRecord
  Lab 1a: Getting Oriented               Lab 3a: Using ActiveRecord
  1.4 Databases                          3.2 Validations
  1.5 Scaffolding                        Lab 3b: Creating a Validation
  Lab 1b: Scaffolding                    3.3 Questions
  Lab 1c: More Scaffolding              1:45 - 2:00 BREAK
  1. 6 Questions                        2:00 - 3:00 UNIT 4
 10:30 - 10:45 BREAK                     4.1 Associations
 10:45 - 12:00 UNIT 2                    Lab 4a: Editing the Model
  2.1 What is MVC?                       4.2 Finishing Up
  Lab 2a: Working with Views             Lab 4b: Changing the View
  Lab 2b: Adding Assignments             4.3 Questions
  2.2 Routes and Rake and redirects     FINISH
  Lab 2c: Changing the Home Page
  Lab 2d: Redirection
Unit 1
1.1 Demo an app            Lab 1b: Scaffolding

1.2 What is Rails?         1. 5 Questions

1.3 Our Environment

Lab 1a: Getting Oriented

1.4 Databases
Intros


• Matt Reider
• Jen Mei
1.1 Demo an App

• Little School House
• Courses Lists (add / edit / delete)
• Assignments (add / edit / delete)
1.2 What is Rails?
• A Framework based on Ruby
 • Huh? Framework?
 • Wha? Ruby?
• A fast way to build web applications
• Fun!
1.3 Our Environment
• We will develop in a browser based editor
• Ctrl-s (or ctrl-shift-s) to save
• Right click to create files / folders
• Console view
• Curriculum view
Lab 1a: Getting Oriented
1. Download & install http://google.com/chrome
2. Open Google Chrome as your browser
3. Get your Lab Environment at http://rubygami.com
4. Click on Console tab
5. Type rails new little_school_house
6. Type cd school_house
7. Type bundle install (and wait)
8. Type rails s
9. Open a new browser tab in Google Chrome
10. Browse to http://(your environment address):3000
11. What do you see? :)
1.4 Databases
•   From Oracle to MySQL and back again

•   Databases consist of Tables

    •   Tables consist of Columns

    •
                                                                               col
                                                                                  um
        Records contain columns of data                                             n:
                                                                                           cou
                                                                                               rse
                                                                                                    _na
                                                                                                       me


        id                   course_name
                                                     id            course_id      course_name
         1                        Biology                1             1                 proteins

         2                        History                2             1              cell organelles
                                                         3             1                  DNA
         3                       Literature


                                              Table:                                         ord lles)
                                                     assignme                          rec rgane
                         urses                               nts                           ll o
                     : co                                                             , ce
                  ble                                                          (2,1
             Ta
1.5 Scaffolding
• A simple command
• Creates HTML, CSS, Test stuff, DB Tables, & Ruby!
• Is a generic start for building an application
       rails generate scaffold course
       title:string description:text
Lab 1b: Scaffolding
1. In your Lab Environment, go to the Console tab.
2. Press ctrl-c and [enter] to make sure you have a prompt
3. Create your application by typing (all on one line):
   rails generate scaffold course title:string
   description:text
4. Add the database from your scaffold by typing:
   rake db:migrate
5. Run the server again:
   rails server
6. Browse to http://(your environment address):3000/courses.
7. Pretend you are a user and add, edit, and delete courses
Lab 1c: More Scaffolding
1. In your Lab Environment, go to the Console tab.
2. Press ctrl-c and [enter] to make sure you have a prompt
3. Now that we have courses, we’re going to add assignments to
   our application. Do this by typing (all on one line):
   rails generate scaffold assignment
   description:text assigned_on:date
   due_on:date
4. Update the database by by typing:
   rake db:migrate
5. Run the server again:
   rails server
6. Browse to http://(your environment address):3000/assignments.
7. Pretend you are a user and add, edit, and delete assignments
1.6 Questions
BREAK
Unit 2
2.1 What is MVC

Lab 2a Working with Views

2.2 Routes

Lab 2b Changing the Home Directory

2.3 Questions
2.1 What is MVC?
• The smart way to build applications
• Separates Business Logic, HTML, and Actions
 • Model: talks to database
 • View: displays information
 • Controller: responds when user does something
2.1 What is MVC?

                            Hey Model,
                             can I have
                            some data?



                     CONTROLLER


            Hey View,
           can you show
   VIEW     the data?               MODEL


   Sure!
                                   Sure, here's
                                  some data...
Lab 2a: Working with Views
1. Browse to http://(your environment address):3000/courses
2. Make sure you have at least one course by clicking on show
3. Click the Editor tab in your Lab Environment
4. Open little_school_house/app/views/courses/show.html.erb
5. Turn the title into a header by putting h1 tags around it (delete lines in
   red; type lines in blue):
   <p>
    <b>Title:</b>
    <%= @course.title %>
   </p>
   <h1><%= @course.title %></h1>
6. Also, remove the “Description” label:
      <b>Description:</b>
7. Run the server again:
   rails server
8. View the changes.
Lab 2b: Adding assignments
1. Click the Editor tab in your Lab Environment
2. Open up little_school_house/app/views/courses/show.html.erb
3. Add in placeholders for assignments: (new code is in blue):
   <p>
    <%= @course.description %>
   </p>
   <h2>Assignments</h2>
   <ul>
     <li>2011-04-01: This quick brown fox jumps
   over the lazy dog.</li>
     <li>2011-04-08: After the jumping.</li>
   </ul>
   <%= link_to 'Edit', edit_course_path(@course) %> |
4. Click the Console tab and run the server again to look at your
   changes.
2.2 Routes
• Looks at which URL a user clicked on
• Decides which Controller to use based on the URL
• Can set root (home) page
       root :to =>"courses#index"
Lab 2c: Changing the Home Directory
1. In the Console tab, run the server if it isn’t running already:
   rails server
2. Browse to http://(your environment address):3000/. Notice that
   you get the default page.
3. In the Editor tab, delete the file public/index.html.
4. Reload the page the in the browser and notice that you get an
   error.
5. In the Editor tab, edit the file config/routes.rb. Add the line in
   blue below:

   resources :courses
   root :to => 'courses#index'
6. In the browser, reload the page. Notice that your page now
   shows up.
Lab 2d: Redirection
1. In the Editor tab, edit config/routes.rb again to use a redirect
   (changed text in blue):

   root :to => redirect("/courses")
2. In the browser, reload the page. Notice that the front page now
   redirects to /courses.
2.3 Questions
LUNCH
Unit 3
3.1 ActiveRecord

Lab 3a Using ActiveRecord

3.2 Validations

Lab 3b Creating a Validation

3.3 Questions
3.1 ActiveRecord
• The Rails way of talking to a database
• Let’s you switch databases without worrying
• Used in Models
    • drawing_101 = Course.new(:title =>
       “Drawing 101”, :description => “Learn
       to draw”)
    • drawing_101.save!
Lab 3a: Using ActiveRecord
1. Click on the Console tab.
2. Click control-c if the server is running.
3. To go into the Rails console, type:
   rails console
4. Try typing these commands:
   • c = Course.first
   • c.title
   • courses = Course.all
   • courses.class
   • drawing_101 = Course.new(:title =>
      “Drawing 101”, :description => “Learn to
      draw”)
   • drawing_101.save!
3.2 Validations
• Protects the database from garbage data
• Belongs in a Model
• Complains if user doesn’t enter clean data:
 • 45-344-2 *not a valid phone number
 • mreider@engine.yard *not a valid email address
validates_length_of :title,
    :within => 5..254,
    :too_short => "Please pick a longer title.",
    :too_long => "Title is too long! Please be more concise"
Lab 3b: Using Validations
1. Click the Editor tab in your Lab Environment
2. Open file app/models/course.rb.
3. Add the following line (new text highlighted in blue):

   class Course < ActiveRecord::Base
     validates_length_of :title,
       :within => 5..254,
       :too_short => "Please pick a longer
   title.",
       :too_long => "Your title is too long!
   Please be more concise"

   end
4. In your browser, try adding a course that has a name shorter
   than 5 characters or longer than 254 characters.
3.3 Questions
BREAK
Unit 4
4.1 Associations

Lab 4-1 Editing the Model

4.2 Putting it all together

Lab 4-2 Making UI changes

4.3 Questions
4.1 Associations
• Creates a relationship between Models
• Represents the relationship between database tables
       belongs_to
       has_one
       has_many

  a course has_many assignments    an assignment belongs_to courses

        id          course_name         id      course_id   course_name
                                        1           1          proteins
        1              Biology
                                        2           1       cell organelles
        2              History          3           1           DNA

        3             Literature
Lab 4-1a: Making database changes
1. In the Console tab, click control-c to exit the server if it’s
   running. Create a new migration by typing:

   rails generate migration
   add_course_id_to_assignments


2. In the Editor tab, open the file that was generated (under the
   db/migrations directory). Edit it to include (new text in blue):
   class AddCourseIdToAssignments < ActiveRecord::Migration
     def self.up
       add_column :assignments, :course_id, :integer
     end
     def self.down
       remove_column :assignments, :course_id
     end

3. In the Console tab, type:
   rake db:migrate
Lab 4-1b: Editing the Models
1. In the Editor tab, edit app/models/course.rb (new text in blue):

   class Course < ActiveRecord::Base
     has_many :assignments


2. Also edit the app/models/assignment.rb:
   class Assignment < ActiveRecord::Base
      belongs_to :course
Lab 4-1c: Testing changes
1. In the Console tab, type control-C to exit server if running.
   Then go into the rails console:

   rails console
2. Create a new course and add some assignments to it
   (comments denoted by “#”):
   c = Course.create!(:title =>
   c.assignments # Should show a blank array: []
   c.assignments.create!(
     :description => "Figure drawing",
     :due_on => 1.week.from_now,
     :assigned_on => Date.today
   )
   c.assignments # Should show the new assignment
4.2 Putting it all together
• Modify routes to show nested structure.
• Modify course show view to list assignments.
• Modify Assignment creation UI.
Lab 4-2a: Modifying routes
1. In the Editor tab, edit config/routes.rb. Nest assignments inside
   of courses, like so:

   LittleSchoolHouse::Application.routes.draw do
     resources :courses do
       resources :assignments
     end
     root :to => redirect("/courses")
Lab 4-2b: Modifying the course show view
1. In the Editor tab, edit app/views/courses/show.html.erb. Replace the
   static list that we added earlier with this code (changes in blue). We will
   also add a link to create a new assignment:

   <h2>Assignments</h2>
   <ul>
     <% @course.assignments.each do |assignment| %>
        <li>
   <%= "#{assignment.due_on}: #{assignment.description}" %>
        </li>
     <% end %>
   </ul>
   <%= link_to "Create a new assignment",
        new_course_assignment_path(@course) %>
Lab 4-2c: Modifying the new assignment
1. In the Editor tab, edit app/views/assignment/new.html.erb.
   Since the routes have changed, we need to change the link for
   ‘Back’. Make the change in blue:
    <%= link_to 'Back', course_path(@course) %>

2. We will also need to change the form itself, which is in a partial.
   Edit it by opening up app/views/assignment/_form.html.erb. Edit
   the form so that it reflects that an assignment belongs to a
   course. Make the changes in blue (make certain to include the
   square brackets ([])):

      <%= form_for([@course, @assignment]) do |f| %>
Lab 4-2d: Modifying the controller
1. In the Editor tab, edit app/controllers/assignments_controller.rb.
   Change the new method (delete line in red; add lines in blue):

   def new
     @assignment = Assignment.new
     @course = Course.find(params[:course_id])
     @assignment = @course.assignments.build

2. Now let’s make a similar change to the create method plus one other
   change:
   def create
     @assignment = Assignment.new(params[:assignment])
     @course = Course.find(params[:course_id])
     @assignment = @course.assignments.build(params[:assignment])
       respond_to do |format|
         if @assignment.save
           format.html
   { redirect_to(course_path(@course), :notice => 'Assignment was
   successfully created.') }
Lab 4-2e:Viewing changes
1. In the Console tab, run the server again:
   rails server
2. In the browser, go to the show page of a course. Add an
   assignment.
4.3 Questions
FINISH

Mais conteúdo relacionado

Semelhante a Web20

Lecture 01 variables scripts and operations
Lecture 01   variables scripts and operationsLecture 01   variables scripts and operations
Lecture 01 variables scripts and operationsSmee Kaem Chann
 
Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Shahrzad Peyman
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docxhoney725342
 
Comp 220 ilab 6 of 7
Comp 220 ilab 6 of 7Comp 220 ilab 6 of 7
Comp 220 ilab 6 of 7ashhadiqbal
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Abdul Hannan
 
Why re-use core classes?
Why re-use core classes?Why re-use core classes?
Why re-use core classes?Levi Waldron
 
How to win data science competitions with Deep Learning
How to win data science competitions with Deep LearningHow to win data science competitions with Deep Learning
How to win data science competitions with Deep LearningSri Ambati
 
Webinar: From Frustration to Fascination: Dissecting Replication
Webinar: From Frustration to Fascination: Dissecting ReplicationWebinar: From Frustration to Fascination: Dissecting Replication
Webinar: From Frustration to Fascination: Dissecting ReplicationHoward Greenberg
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Umair Amjad
 
BIS 245 Lessons in Excellence / bis245.com
BIS 245 Lessons in Excellence / bis245.comBIS 245 Lessons in Excellence / bis245.com
BIS 245 Lessons in Excellence / bis245.comkopiko33
 
BIS 245 OUTLET Inspiring Innovation--bis245outlet.com
 BIS 245 OUTLET Inspiring Innovation--bis245outlet.com BIS 245 OUTLET Inspiring Innovation--bis245outlet.com
BIS 245 OUTLET Inspiring Innovation--bis245outlet.comwilliamwordsworth45
 
BIS 245 OUTLET Achievement Education--bis245outlet.com
BIS 245 OUTLET Achievement Education--bis245outlet.comBIS 245 OUTLET Achievement Education--bis245outlet.com
BIS 245 OUTLET Achievement Education--bis245outlet.comagathachristie179
 
BIS 245 OUTLET Introduction Education--bis245outlet.com
BIS 245 OUTLET Introduction Education--bis245outlet.comBIS 245 OUTLET Introduction Education--bis245outlet.com
BIS 245 OUTLET Introduction Education--bis245outlet.comagathachristie291
 

Semelhante a Web20 (20)

Lecture 01 variables scripts and operations
Lecture 01   variables scripts and operationsLecture 01   variables scripts and operations
Lecture 01 variables scripts and operations
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6
 
Mit6 094 iap10_lec01
Mit6 094 iap10_lec01Mit6 094 iap10_lec01
Mit6 094 iap10_lec01
 
Intro to Rails 4
Intro to Rails 4Intro to Rails 4
Intro to Rails 4
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docx
 
Comp 220 ilab 6 of 7
Comp 220 ilab 6 of 7Comp 220 ilab 6 of 7
Comp 220 ilab 6 of 7
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
 
Why re-use core classes?
Why re-use core classes?Why re-use core classes?
Why re-use core classes?
 
How to win data science competitions with Deep Learning
How to win data science competitions with Deep LearningHow to win data science competitions with Deep Learning
How to win data science competitions with Deep Learning
 
Webinar: From Frustration to Fascination: Dissecting Replication
Webinar: From Frustration to Fascination: Dissecting ReplicationWebinar: From Frustration to Fascination: Dissecting Replication
Webinar: From Frustration to Fascination: Dissecting Replication
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3
 
Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 
BIS 245 Lessons in Excellence / bis245.com
BIS 245 Lessons in Excellence / bis245.comBIS 245 Lessons in Excellence / bis245.com
BIS 245 Lessons in Excellence / bis245.com
 
BIS 245 OUTLET Inspiring Innovation--bis245outlet.com
 BIS 245 OUTLET Inspiring Innovation--bis245outlet.com BIS 245 OUTLET Inspiring Innovation--bis245outlet.com
BIS 245 OUTLET Inspiring Innovation--bis245outlet.com
 
BIS 245 OUTLET Achievement Education--bis245outlet.com
BIS 245 OUTLET Achievement Education--bis245outlet.comBIS 245 OUTLET Achievement Education--bis245outlet.com
BIS 245 OUTLET Achievement Education--bis245outlet.com
 
BIS 245 OUTLET Introduction Education--bis245outlet.com
BIS 245 OUTLET Introduction Education--bis245outlet.comBIS 245 OUTLET Introduction Education--bis245outlet.com
BIS 245 OUTLET Introduction Education--bis245outlet.com
 

Web20

  • 1. Rails at a Snail’s Pace Matt Reider Jen-Mei Wu
  • 2. 9:00 - 10:30 UNIT 1 Agenda 2.3 Questions 1.1 Demo an app 12:00 LUNCH 1.2 What is Rails? 1:00 - 1:45 UNIT 3 1.3 Intro Environment 3.1 ActiveRecord Lab 1a: Getting Oriented Lab 3a: Using ActiveRecord 1.4 Databases 3.2 Validations 1.5 Scaffolding Lab 3b: Creating a Validation Lab 1b: Scaffolding 3.3 Questions Lab 1c: More Scaffolding 1:45 - 2:00 BREAK 1. 6 Questions 2:00 - 3:00 UNIT 4 10:30 - 10:45 BREAK 4.1 Associations 10:45 - 12:00 UNIT 2 Lab 4a: Editing the Model 2.1 What is MVC? 4.2 Finishing Up Lab 2a: Working with Views Lab 4b: Changing the View Lab 2b: Adding Assignments 4.3 Questions 2.2 Routes and Rake and redirects FINISH Lab 2c: Changing the Home Page Lab 2d: Redirection
  • 3. Unit 1 1.1 Demo an app Lab 1b: Scaffolding 1.2 What is Rails? 1. 5 Questions 1.3 Our Environment Lab 1a: Getting Oriented 1.4 Databases
  • 5. 1.1 Demo an App • Little School House • Courses Lists (add / edit / delete) • Assignments (add / edit / delete)
  • 6. 1.2 What is Rails? • A Framework based on Ruby • Huh? Framework? • Wha? Ruby? • A fast way to build web applications • Fun!
  • 7. 1.3 Our Environment • We will develop in a browser based editor • Ctrl-s (or ctrl-shift-s) to save • Right click to create files / folders • Console view • Curriculum view
  • 8. Lab 1a: Getting Oriented 1. Download & install http://google.com/chrome 2. Open Google Chrome as your browser 3. Get your Lab Environment at http://rubygami.com 4. Click on Console tab 5. Type rails new little_school_house 6. Type cd school_house 7. Type bundle install (and wait) 8. Type rails s 9. Open a new browser tab in Google Chrome 10. Browse to http://(your environment address):3000 11. What do you see? :)
  • 9. 1.4 Databases • From Oracle to MySQL and back again • Databases consist of Tables • Tables consist of Columns • col um Records contain columns of data n: cou rse _na me id course_name id course_id course_name 1 Biology 1 1 proteins 2 History 2 1 cell organelles 3 1 DNA 3 Literature Table: ord lles) assignme rec rgane urses nts ll o : co , ce ble (2,1 Ta
  • 10. 1.5 Scaffolding • A simple command • Creates HTML, CSS, Test stuff, DB Tables, & Ruby! • Is a generic start for building an application rails generate scaffold course title:string description:text
  • 11. Lab 1b: Scaffolding 1. In your Lab Environment, go to the Console tab. 2. Press ctrl-c and [enter] to make sure you have a prompt 3. Create your application by typing (all on one line): rails generate scaffold course title:string description:text 4. Add the database from your scaffold by typing: rake db:migrate 5. Run the server again: rails server 6. Browse to http://(your environment address):3000/courses. 7. Pretend you are a user and add, edit, and delete courses
  • 12. Lab 1c: More Scaffolding 1. In your Lab Environment, go to the Console tab. 2. Press ctrl-c and [enter] to make sure you have a prompt 3. Now that we have courses, we’re going to add assignments to our application. Do this by typing (all on one line): rails generate scaffold assignment description:text assigned_on:date due_on:date 4. Update the database by by typing: rake db:migrate 5. Run the server again: rails server 6. Browse to http://(your environment address):3000/assignments. 7. Pretend you are a user and add, edit, and delete assignments
  • 14. BREAK
  • 15. Unit 2 2.1 What is MVC Lab 2a Working with Views 2.2 Routes Lab 2b Changing the Home Directory 2.3 Questions
  • 16. 2.1 What is MVC? • The smart way to build applications • Separates Business Logic, HTML, and Actions • Model: talks to database • View: displays information • Controller: responds when user does something
  • 17. 2.1 What is MVC? Hey Model, can I have some data? CONTROLLER Hey View, can you show VIEW the data? MODEL Sure! Sure, here's some data...
  • 18. Lab 2a: Working with Views 1. Browse to http://(your environment address):3000/courses 2. Make sure you have at least one course by clicking on show 3. Click the Editor tab in your Lab Environment 4. Open little_school_house/app/views/courses/show.html.erb 5. Turn the title into a header by putting h1 tags around it (delete lines in red; type lines in blue): <p> <b>Title:</b> <%= @course.title %> </p> <h1><%= @course.title %></h1> 6. Also, remove the “Description” label: <b>Description:</b> 7. Run the server again: rails server 8. View the changes.
  • 19. Lab 2b: Adding assignments 1. Click the Editor tab in your Lab Environment 2. Open up little_school_house/app/views/courses/show.html.erb 3. Add in placeholders for assignments: (new code is in blue): <p> <%= @course.description %> </p> <h2>Assignments</h2> <ul> <li>2011-04-01: This quick brown fox jumps over the lazy dog.</li> <li>2011-04-08: After the jumping.</li> </ul> <%= link_to 'Edit', edit_course_path(@course) %> | 4. Click the Console tab and run the server again to look at your changes.
  • 20. 2.2 Routes • Looks at which URL a user clicked on • Decides which Controller to use based on the URL • Can set root (home) page root :to =>"courses#index"
  • 21. Lab 2c: Changing the Home Directory 1. In the Console tab, run the server if it isn’t running already: rails server 2. Browse to http://(your environment address):3000/. Notice that you get the default page. 3. In the Editor tab, delete the file public/index.html. 4. Reload the page the in the browser and notice that you get an error. 5. In the Editor tab, edit the file config/routes.rb. Add the line in blue below: resources :courses root :to => 'courses#index' 6. In the browser, reload the page. Notice that your page now shows up.
  • 22. Lab 2d: Redirection 1. In the Editor tab, edit config/routes.rb again to use a redirect (changed text in blue): root :to => redirect("/courses") 2. In the browser, reload the page. Notice that the front page now redirects to /courses.
  • 24. LUNCH
  • 25. Unit 3 3.1 ActiveRecord Lab 3a Using ActiveRecord 3.2 Validations Lab 3b Creating a Validation 3.3 Questions
  • 26. 3.1 ActiveRecord • The Rails way of talking to a database • Let’s you switch databases without worrying • Used in Models • drawing_101 = Course.new(:title => “Drawing 101”, :description => “Learn to draw”) • drawing_101.save!
  • 27. Lab 3a: Using ActiveRecord 1. Click on the Console tab. 2. Click control-c if the server is running. 3. To go into the Rails console, type: rails console 4. Try typing these commands: • c = Course.first • c.title • courses = Course.all • courses.class • drawing_101 = Course.new(:title => “Drawing 101”, :description => “Learn to draw”) • drawing_101.save!
  • 28. 3.2 Validations • Protects the database from garbage data • Belongs in a Model • Complains if user doesn’t enter clean data: • 45-344-2 *not a valid phone number • mreider@engine.yard *not a valid email address validates_length_of :title, :within => 5..254, :too_short => "Please pick a longer title.", :too_long => "Title is too long! Please be more concise"
  • 29. Lab 3b: Using Validations 1. Click the Editor tab in your Lab Environment 2. Open file app/models/course.rb. 3. Add the following line (new text highlighted in blue): class Course < ActiveRecord::Base validates_length_of :title, :within => 5..254, :too_short => "Please pick a longer title.", :too_long => "Your title is too long! Please be more concise" end 4. In your browser, try adding a course that has a name shorter than 5 characters or longer than 254 characters.
  • 31. BREAK
  • 32. Unit 4 4.1 Associations Lab 4-1 Editing the Model 4.2 Putting it all together Lab 4-2 Making UI changes 4.3 Questions
  • 33. 4.1 Associations • Creates a relationship between Models • Represents the relationship between database tables belongs_to has_one has_many a course has_many assignments an assignment belongs_to courses id course_name id course_id course_name 1 1 proteins 1 Biology 2 1 cell organelles 2 History 3 1 DNA 3 Literature
  • 34. Lab 4-1a: Making database changes 1. In the Console tab, click control-c to exit the server if it’s running. Create a new migration by typing: rails generate migration add_course_id_to_assignments 2. In the Editor tab, open the file that was generated (under the db/migrations directory). Edit it to include (new text in blue): class AddCourseIdToAssignments < ActiveRecord::Migration def self.up add_column :assignments, :course_id, :integer end def self.down remove_column :assignments, :course_id end 3. In the Console tab, type: rake db:migrate
  • 35. Lab 4-1b: Editing the Models 1. In the Editor tab, edit app/models/course.rb (new text in blue): class Course < ActiveRecord::Base has_many :assignments 2. Also edit the app/models/assignment.rb: class Assignment < ActiveRecord::Base belongs_to :course
  • 36. Lab 4-1c: Testing changes 1. In the Console tab, type control-C to exit server if running. Then go into the rails console: rails console 2. Create a new course and add some assignments to it (comments denoted by “#”): c = Course.create!(:title => c.assignments # Should show a blank array: [] c.assignments.create!( :description => "Figure drawing", :due_on => 1.week.from_now, :assigned_on => Date.today ) c.assignments # Should show the new assignment
  • 37. 4.2 Putting it all together • Modify routes to show nested structure. • Modify course show view to list assignments. • Modify Assignment creation UI.
  • 38. Lab 4-2a: Modifying routes 1. In the Editor tab, edit config/routes.rb. Nest assignments inside of courses, like so: LittleSchoolHouse::Application.routes.draw do resources :courses do resources :assignments end root :to => redirect("/courses")
  • 39. Lab 4-2b: Modifying the course show view 1. In the Editor tab, edit app/views/courses/show.html.erb. Replace the static list that we added earlier with this code (changes in blue). We will also add a link to create a new assignment: <h2>Assignments</h2> <ul> <% @course.assignments.each do |assignment| %> <li> <%= "#{assignment.due_on}: #{assignment.description}" %> </li> <% end %> </ul> <%= link_to "Create a new assignment", new_course_assignment_path(@course) %>
  • 40. Lab 4-2c: Modifying the new assignment 1. In the Editor tab, edit app/views/assignment/new.html.erb. Since the routes have changed, we need to change the link for ‘Back’. Make the change in blue: <%= link_to 'Back', course_path(@course) %> 2. We will also need to change the form itself, which is in a partial. Edit it by opening up app/views/assignment/_form.html.erb. Edit the form so that it reflects that an assignment belongs to a course. Make the changes in blue (make certain to include the square brackets ([])): <%= form_for([@course, @assignment]) do |f| %>
  • 41. Lab 4-2d: Modifying the controller 1. In the Editor tab, edit app/controllers/assignments_controller.rb. Change the new method (delete line in red; add lines in blue): def new @assignment = Assignment.new @course = Course.find(params[:course_id]) @assignment = @course.assignments.build 2. Now let’s make a similar change to the create method plus one other change: def create @assignment = Assignment.new(params[:assignment]) @course = Course.find(params[:course_id]) @assignment = @course.assignments.build(params[:assignment]) respond_to do |format| if @assignment.save format.html { redirect_to(course_path(@course), :notice => 'Assignment was successfully created.') }
  • 42. Lab 4-2e:Viewing changes 1. In the Console tab, run the server again: rails server 2. In the browser, go to the show page of a course. Add an assignment.

Notas do Editor

  1. Talking Points:\nThis is for Snails. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n