railsbridge rails workshop curriculum

Upload: openworkshops

Post on 30-May-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    1/12

    Rails CurriculumFrom DevchixWiki

    Contents

    1 Build and deploy a web application1.1 Let's build a web application

    2 Make it your own2.1 Edit index page2.2 Awesome! Let's ship it!

    3 A Closer Look at the Features

    4 First Feature: Adding topics4.1 Scaffolding4.2 A Quick Look at Your Database4.3 Deploy Your Application

    5 What did we just do?5.1 A closer look

    6 Routes7 Next feature: creating a topic

    7.1 Controller: adjusting the flow of your application8 Next feature: the Topics page9 Next feature: allow voting on a topic

    9.1 How will we build this feature?9.2 Rails associations9.3 Add votes9.4 Allow people to vote

    Build and deploy a web application

    We will build a web application that allows people to create topics and vote on them. Ultimately, this

    application will have registration and authentication and a variety of other features. Today we will focus onbuilding the core features of topics and votes.

    Here is the UI ([User Interface (http://en.wikipedia.org/wiki/User_interface|) ]) design for the application:

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    2/12

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    3/12

    vendor/ A place for third-party code

    Run the web app:

    ruby script/server

    Point your web browser to http://localhost:3000, and see your web app actually there!

    Make it your own

    Start Komodo EditFile -> New -> New Project...Open your new "suggestotron" directoryView -> Tabs & Sidebars -> Projects

    Edit index page

    Note that the page you are seeing at http://localhost:3000 is in public/index.htmlMake a change, save, and reload

    Awesome! Let's ship it!

    From your new "suggestotron" directory, create a local git repository:

    git initgit add .git commit -m 'basic web application'

    Then deploy to heroku:

    heroku creategit push heroku master

    Notice the URL that heroku reports after you typed "heroku create." Type this URL in your browser to seeyour application on the Web.

    A Closer Look at the Features

    The features have been defined in the /features directory. These were written for you in advance as aspecification of the application.

    One of the basic features that we might build first is defined in the topics.feature file in the featuresdirectory:

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    4/12

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    5/12

    tables (add/remove/rename columns) and even modifying data.

    Now let's set up the database for the test by running the migration file on the test database:

    rake db:migrate RAILS_ENV=test

    Run the cucumber feature again (and the first one should pass)

    cucumber features/topics.feature

    Now let's look at the feature we created. We will typically do so in the development environment.Create the topics table:

    rake db:migrate

    Then start your server:

    ruby script/server

    And point your browser to http://localhost:3000/topics

    Congratulations! You have built a web application that works with a relational database.

    A Quick Look at Your Database

    You can access the database directly on your local machine. For this class were using SQLite, the GUItool you installed that lets you inspect the database. In Firefox, select "Tools -> SQLite Manager."

    Click the open folder icon !or choose Database -> Connect Database to open suggestotron/db/development.sqlite3

    In SQLite, you can choose Browse & Search to interactively explore the database or Execute SQL totype SQL commands.

    You can also access the database through the command line:

    ruby script/dbconsole

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    6/12

    Common SQL Commands

    sqlite MySql

    list tables in current db .tables show tables;

    show SQL for table create list columns

    .schema

    .schema people

    show create table topics;

    describe topics;

    exit command line tool .quit exit

    show all rows in table select * from topics;

    show number of rows select count(*) from topics;

    show matching record select * from topic where title = "My Topic";

    Deploy Your Application

    Dont forget, "commit early, deploy often." Here's how:

    git add .git commit -m 'topic crud'git push heroku masterheroku rake db:migrate

    Congratulations! You have built and deployed a web application that works with a relational database.

    What did we just do?

    Rails implements a very specific notion of the Model-View-Controller pattern which guides how youbuild a web application.

    Model

    represents what is in the databaseActiveRecord

    View

    the model rendered as HTMLActionView, erb

    Controller

    receives HTTP actions (GET, POST, PUT, DELETE)decides what to do, such as rendering a view

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    7/12

    ActionController

    When you executed the script/generate command, Rails generated files that implement a model, views, anda controller for the topics feature.

    The Model

    create app/models/topic.rbcreate db/migrate/20090611073227_create_topics.rb

    Four (4) Views

    create app/views/topics/index.html.erbcreate app/views/topics/show.html.erbcreate app/views/topics/new.html.erbcreate app/views/topics/edit.html.erb

    The Controller

    create app/controllers/topics_controller.rbroute map.resources :topics

    A closer look

    Rails allows you to easily invoke irb with all of the Rails libraries and your application code loaded:

    ruby script/console

    Lets look at the model that is defined here: app/models/topic.rb

    >> t = Topic.new=> #>> t.title = "My topic"=> "My topic">> t.description = "this is really cool"=> "this is really cool">> t.save

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    8/12

    Notice that the Topic class has title and description attributes which you did not need to explicitly declarein the class. This is handled by ActiveRecord which implements ORM (Object Relational Mapping) inRails.

    Routes

    Rails routes control how URLs map to code. We can use rake to list the relationships between routes andcontrollers.

    $ rake routestopics GET /topics(.:format) {:action=>"index", :controller=>"topics" }

    POST /topics(.:format) {:action=>"create", :controller=>"topics" }new_topic GET /topics/new(.:format ) {:action=>"new", :controller=>"topics "}edit_topic GET /topics/:id/edit(.: format) {:action=>"edit", :controller=>"topics"}

    topic GET /topics/:id(.:format ) {:action=>"show", :controller=>"topic s"}PUT /topics/:id(.:format ) {:action=>"update", :controller=>"topics" }DELETE /topics/:id(.:format ) {:action=>"destroy", :controller=>"topics "}

    /:controller/:action/:id/:controller/:action/:id(.:format)

    Each method in the controller will take an HTTP request, usually find some data in the database (via anActiveRecord model) and render a view or re-direct to another action.

    Next feature: creating a topic

    Let's run the next feature and see what we need to build next.

    cucumber features/topics.feature

    Scenario: Creating a topicGiven I go to topicsAnd I follow "New topic"When I fill in "Title" with "Rails Fixtures"And I fill in "Description" with "Introduce how to add test data with fixtures."And I press "Create"Then I should see "Rails Fixtures"And I should see a "New topic" link

    Run the server ( script/server ), look at the app (http://localhost:3000/topics/), and see how the scaffoldtemplate differs from the desired application as we've described it above using cucumber. What we want isthe application to show the list of topics after the user creates a topic by completing the form. However,the scaffold displays instead a page showing only the individual topic the user just created.

    Controller: adjusting the flow of your application

    We looked at the scaffold-generated code a little earlier. To change the behavior and make the feature actas desired, we will look more closely now at the controller, which controls the general flow of yourapplication; for instance, which page is displayed when the user clicks a link or a button.

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    9/12

    Open app/controllers/topics_controller.rb and look at the new and create actions.

    Notice that in create there is a redirect to a single topic, format.html { redirect_to(@topic)} . We want to redirect instead to the list of topics:

    format.html { redirect_to(topics_path) }

    Now run your feature again with cucumber and it should pass

    cucumber features/topics.feature

    Next feature: the Topics page

    Note that for this next set of feature scenarios we have a "Background" set of steps which will be executed

    before each scenario in the file. Since they depend on behavior that already works, they're rendered inreen (pass).

    Scenario: Clicking on the topic titleWhen I follow "Rails Fixtures"Then I should see "Introduce how to add test data with fixtures."And I should not see "add a topic"

    Run the scenario and watch it fail:

    cucumber features/topics_list_and_details.feature

    In the last scenario we made it so the app redirected to "topics_path" after create. So, we expect thatwe will need to fix the error in that page. We can use rake routes to find the controller action, thenwe can see that the default view is rendered. The error is in views/topics/index.html.erb :

    Run the scenario again and see that the "Clicking on the topic title" passes, but we still have onefailure which can be addressed in the same fileOpen views/topics/index.html.erb and change "Destroy" to "Delete".

    Next feature: allow voting on a topic

    Feature: VotesIn order to determine which talk to givepeople need to be able to vote for the ones they like

    Background: Make sure that we have a topic

    Given I go to topicsAnd I follow "New topic"

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    10/12

    When I fill in "Title" with "Rails Fixtures"And I fill in "Description" with "Introduce how to add test data with fixtures."And I press "Create"

    Scenario: viewing votes already cast

    When I go to topicsThen I should see "0 votes"

    Scenario: voting on a topic

    When I follow "+1"Then I should see "1 vote"

    cucumber features/votes.feature

    How will we build this feature?

    Each vote will be an object (row in database table)When someone votes on a topic, we'll create a new vote object and save itEach vote is associated with a specific topic

    Rails associations

    * Topic has_many :votes* Vote belongs_to :topics

    Add votes

    Use cucumber to run the "votes" feature

    cucumber features/votes.feature

    We will use the resource generation script to create a model and controller (no views):

    script/generate resource vote topic_id:integer

    And then we migrate

    rake db:migrate db:test:prepare

    The script creates files with:

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    11/12

    model (including migration, unit, fixture)controller (and route) with no code

    Add code to to your models ( /app/models/vote.rb and /app/models/topic.rb ) to create theassociations:

    class Topic < ActiveRecord::Basehas_many :votes

    end

    class Vote < ActiveRecord::Basebelongs_to :topic

    end

    Check it out in irb ( script/console ):

    >> t = Topic.new=> #>> t.votes=> []>> t.votes.build=> #>> t.votes=> [#]>> t.save=> true>> t.votes=> [#

  • 8/9/2019 RailsBridge Rails Workshop Curriculum

    12/12

    if vote.saveflash[:notice] = 'Vote was successfully created.'

    elseflash[:notice] = 'Sorry we could not count your vote.'

    endredirect_to(topics_path)

    endend

    Retrieved from "http://wiki.devchix.com/index.php?title=Rails_Curriculum"

    This page was last modified on 27 February 2010, at 03:39.Content is available under Attribution 3.0 Unported.