Welcome, Guest User :: Click here to login

Logo 67272

Lab 3: SimpleQuotes

Due Date: February 21

Objectives

  • Learn to build a basic but functioning Rails app
  • Improve familiarity with basic git commands
  • Practice working with sqlite3 databases
  • Learn how to style a Rails app
  • Be able to submit project code to a remote repo

README.md

Part 1: Getting Started

  1. Create a new rails application called "SimpleQuotes" and initialize a blank git repository inside the app:

     rails new SimpleQuotes
     cd SimpleQuotes
     git init .
    
  2. Add all the files generated by rails to the repo and verify that all files are staged with the command git status. Commit these files by typing to git and verify again with git status.

     git add .
     git commit -m 'Base rails app'
    
  3. Checkout a new branch called "quote". We will merge this back into master later.

     git checkout -b quote
    
  4. Create the Quote model and scaffolding using the rails generator. (Substitute the correct values):

     rails generate scaffold <Model> <attribute>:<data type>
    

    Your model should be Quote, with body:string and source:string. When generating the scaffold, multiple attributes (with colon and data type) are separated by a single space.

  5. Visit the Rails API documentation from your browser for reference.

  6. Open your rails project in VS Code. From the terminal you can use the code . command.

    Mac users will need to add the command to their path (it is not hard) but this should already work on WSL.

  7. Open the config/database.yml file and change the name of the development database to match the following:

    development:
      # ... other stuff
      database: db/quotes_dev.sqlite3
    

    Do not change anything else in the file!

  8. Go to the db/migrate directory and verify there is a file named <somenumber>_create_quotes.rb. Open this file and make sure the content is accurate.

    Set the default value of source to "Anonymous". To do this, change the line with :source to

    t.string :source, default: "Anonymous"
    
  9. Migrate the database:

     rails db:migrate
    
  10. Commit your work with git. First type git status to see what needs to be staged. You will notice that in addition to the config/database.yml change you made, rails automatically edited your routes.rb file to include routing information for the new model you created.

     git status
    

    In addition, there are a number of new files related to the quotes scaffolding that need to be added to the project. Since these are all related, we will add them all at once to the staging level with git add ..

     git add .
    

    Now commit these changes from staging to the repository by typing. Type git log to see a history of the repository changes.

     git commit -m "Quote model scaffolded; db minor edits"
    
  11. Start up the development web server.

     rails server
    
  12. Open up your browser and go to localhost:3000 to view the application.

  13. Add a /quotes to the end of the URL to get to the main quotes page.

  14. Use the web ui to enter in at least three quotes from the famous quotes database. Update one quote. Destroy one quote.

  15. Now that the basic CRUD functionality is working and the app is populated with test data, let's merge it back to the master branch.

     git checkout master
     git merge quote
    

Stop

Show a TA that you have the Rails app set up, that the CRUD functionality of the app is working, and have properly saved the code to git. Make sure the TA initials your sheet.


Part 2: Model, View, and Controller

  1. Download the additional lab materials from github.com.

  2. Unzip the file and familiarize yourself with the contents. Go back to the command line and create a new git branch called 'home' and check out the code to that branch.

     git checkout -b home
    
  3. Add the image quips_n_quotes.png to your app/assets/images directory.

  4. Now we want to edit the application layout (app/views/layouts/application.html.erb).

    Use the following as a template to get you started. Make sure to look at the API documentation before asking a TA for help.

     <html>
       <head>
         <meta http-equiv="Content-type" content="text/html; charset=utf-8">
         <title>Quips and Quotes :: <%= controller.controller_name.capitalize %></title>
         <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    
         <!-- #stylesheet: add my_styles using rails helper function (but not yet...)# -->
    
         <%= javascript_include_tag 'application' %>
         <%= csrf_meta_tag %>
       </head>
    
       <body>
         <div id="wrap">
           <div id="header">
             <%= link_to(image_tag('quips_n_quotes.png'), home_path) %>
            </div>
            <br />
    
            <div id="body">
              <%= yield %>
            </div>
    
            <!-- #footer partial should go here later (but not yet...)# -->
    
         </div>
       </body>
     </html>
    
  5. Make sure Rails can find the new home page by adding the code below to the config/routes.rb file. Add this code right after the resources :quotes line. (You can delete the comments after you read them and clean up the file as well.)

    resources :quotes
    
    get 'home' => 'home#index', as: :home
    root to: 'home#index'
    
  6. Promote these changes to the staging level in git and then commit them to the repository's home branch.

  7. Start the rails server and in browser click on the logo at the top of the page.

    Solve this error on your own. (Just kidding...)

    The problem is that the layout references a 'home_path' to a controller that we have not yet created.

  8. Now we can create a home controller with an index action:

      rails generate controller Home index
    

    This will create a controller called 'home_controller' with an index action as well as the associated view.

  9. Open the Quote model in app/models/quote.rb and add in the method get_random_quote below.

    # Method to get a random quote for home page
    # 
    # @return [Quote]
    #   the random quote 
    def self.get_random_quote
      self.all.to_a[rand(self.all.length)]
    end
    
  10. You might have discovered that the random function is incorrect, since would generate a random number that might be up to the index of the length, which would be out of bounds. You can quickly fix it as follows if you haven't already.

    # Method to get a random quote for home page
    # 
    # @return [Quote]
    #   the random quote 
    def self.get_random_quote
      self.all.to_a[rand(self.all.length) - 1]
    end
    
  11. What's even better, as it turns out you don't even need to generate the number yourself. In fact, Rails provides us with the useful function select, which gets a random element from a relation. Great! You can just replace the inside of the method with the following:

      self.all.sample
    
  12. Let's also add some validations to make sure that all quotes have a source and a body. Add the following code to the quotes model, before get_random_quote method:

      validates_presence_of :body
      validates_presence_of :source
    
  13. Now, let's open the home controller in app/controllers and add a new random quote to the index action by adding the following line to the index method:

       @quote = Quote.get_random_quote
    
  14. Replace the generic contents of app/views/home/index.html.erb with the sample code below. Of course, replace each of the commented erb tags (<%= %>) with either the body or the source of the quote we got in the home controller. Hint: this can be accessed by @quote.<field_name>:

    <p>This site is an eclectic set of (somewhat) famous quotes. Today's quote of the day is as follows:</p>
    <p>&nbsp;</p>
    
    <h1><%= # QUOTE BODY GOES HERE %></h1><br>
    
    <h2><%= # SOURCE GOES HERE %></h2>
    
    <p>&nbsp;</p>
    <%= link_to 'Add a new quote to our list', new_quote_path %>
    
  15. Commit all these changes to git.

  16. Restart the web server and view the site. Reload the home page several times to see new quotes appear.

  17. Add new quotes (try once to skip the body and see the error message that is given) in the quotes section.

  18. Finally, it's time to add a statement of ownership to the footer of every page.

    In the app/views directory create a new directory called partials.

  19. Create a new file in that directory called _footer.html.erb and add the contents shown below.

    <div id="footer">
      <div id="copy">
        Webmaster: <%= # your mail_to link goes here %> 
        Copyright &copy; 2021
      </div>
    </div>
    

    Note that you need to edit the mail_to link so that it displays your name and references your email address.

    This mail_to function will get rendered into pure HTML by the Rails template engine before serving this page to the client's browser.

  20. Go to the application.html.erb file in the layouts directory and replace the #footer partial# comment with an erb tag that renders the partial footer you just created.

    <%= render partial: 'partials/footer' %>
    

    Note that we don't include the _ (underscore) or extension (.html.erb).

  21. Restart the rails application and view your footer. Make sure your name links to your email address.

  22. Now we need to merge these changes onto the master branch. Switch back to the master branch now. Using the command git merge home to pull the contents of the home branch into the master branch.

     git checkout master
     git merge home
    

Stop

Show a TA that your website is working, has a footer and random quote, and that you have committed your changes to git. Make sure the TA initials your sheet.


Part 3: Additional Views

  1. Make sure you have the additional lab materials from part 3 handy before starting this section. Go to the command line and create a new git branch called 'styling' and check out the code to that branch so we can experiment with some new styles.

     git checkout -b styling
    
  2. Add the my_styles.css file to your app/assets/stylesheets directory.

  3. Edit the my_styles.css stylesheet so that the base font is Verdana and font-size is 14px:

    html, body {
      font-family: Verdana;
      font-size: 14px;
    }
    
  4. Edit the h1 tags display text in bold and at a font-size 180% of the base size:

    h1 {
      font-size: 180%;
      line-height: 1.5;
    }
    
  5. When we restart the server, we see the correct information displayed on home/index, but no styling or image can be seen. That’s because we have not yet inserted the stylesheet tags in our application layout file, which is app/views/layouts/application.html.erb. Add this code in place of the stylesheet comment:

    <%= stylesheet_link_tag "my_styles.css" %>
    
  6. Also add this line of code at the bottom of config/initializers/assets.rb:

    Rails.application.config.assets.precompile += %w( my_styles.css )
    
  7. Restart rails server to see the new styling.

  8. Commit to git.


Stop

Show a TA that your rails application has additional styling. Make sure the TA initials your sheet.


Part 4: SQLite Practice

Note: If you are out of time, you may finish this last part outside of lab. You will get full credit for this lab.

  1. Now we will practice interacting with the database directly. Using the SQLite Manager in Firefox, Base, or the command line, open the db/quotes_dev.sqlite3 database.

    If you want to use the command line, you can type rails db as a shortcut to open the database. Typing .quit will return you to the command line. Typing .mode column and .header on will make the output more readable.

  2. Experiment with the interface by adding, deleting and searching for quotes using SQL. When you are ready, demonstrate to a TA that you can perform all three of these operations in SQLite Manager or on the command line.


Stop

Show a TA that you can work with a sqlite3 database. Make sure the TA initials your sheet. You are now finished with the lab.