Ethan Lee
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    <style type="text/css"> @import url("https://use.typekit.net/kwj4ujf.css"); body { background-color: #FF3700; } .reveal h1 { font-size: 3em; } .reveal a { color: white } .reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 { font-family: Gibson, BlinkMacSystemFont, sans-serif; font-weight: 700; color: white; } .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 { font-weight: 600; } .reveal h3 { /*color: rgba(255, 255, 255, 0.7);*/ } .reveal > *, .reveal *, .reveal > * > * { color: white; font-family: Gibson, BlinkMacSystemFont, sans-serif; } .logo { position: absolute; right: 50px; bottom: 50px; width: 75px; z-index: 9999; } .reveal .controls { left: 120px; right: auto; } .reveal .slide-background.stack .slide-background:not(:nth-child(1)) { background-color: white; text-align: left; } .reveal .slides > section.stack > section:not(:first-child) { /*margin-left: -10%; margin-top: -10%;*/ text-align: left; } .reveal .slides > section.stack > section:not(:first-child) * { color: black; font-family: Gibson, BlinkMacSystemFont, sans-serif; } .reveal .slides > section.stack > section:not(:first-child) h1 { font-size: 48pt; color: white; background-color: #FF3700; padding: 5px 20px; display: inline-block; } .reveal code, .reveal pre { font-family: "Source Code Pro", monospace; } </style> <a href="tinyurl.com/fa18-labgroups">tinyurl.com/fa18-labgroups</a> Find your lab groups! ![](https://i.imgur.com/OFSv1H4.jpg) --- # Ruby on Rails DeCal ## Week 4: Deeper into Modeling --- # Update available `npm i -g @calblueprint/whales` * Cleans up after itself * Experimental browser console available at `npm i -g @calblueprint/whales@edge` (Windows users, don't use `@edge`) --- # Let's review! ---- # Lab Review In the lab, we used a **class** to store information in isolated **objects**/instances. ---- # Lab Review This might look a lot like object-oriented programs you've written for CS classes. ```ruby class City attr_accessor :name, :temperature, :description def initialize(city_params) @name = city_params[:name] @temperature = city_params[:temperature] @description = city_params[:description] end end ``` ---- # Lab Review **Moving forward**: What's wrong with this to keep the city around? ```ruby def save $cities << self end ``` ---- # Lab Review Restarting the server will _lose your information_. We'll use a database to store our models. <!-- .element: class="fragment" --> _What are databases?_ <!-- .element: class="fragment" --> ---- # Databases A way of storing structured information in tables **Cities** | ID | Name | Temperature | Description | | -------- | -------- | -------- | ---- | | 1 | Berkeley | 50.4° | partly cloudy | | 2 | Los Angeles | 70.6° | clear | | 3 | New York | 76° | sunny | ---- ![](https://i.imgur.com/5WVaaFY.png) ---- ![](https://i.imgur.com/Ii9FOHl.png) ---- # How do you interact with a database? or... HOW DO YOU INTERACT WITH A DATABASE; ```sql SELECT * FROM STATION WHERE 50 < (SELECT AVG(TEMP_F) FROM STATS WHERE STATION.ID = STATS.ID); ``` ---- # Uh oh That's not fun ---- # Rails does it for you Just getting the first record is easier! ```ruby City.first ``` generates ```sql SELECT * FROM cities ORDER BY cities.id ASC LIMIT 1 ``` --- # Rewind Rails solves two important problems: **modeling** and templating. ---- # `rails generate` This command creates a model class file that we can start using! Here's the syntax: `rails generate model ModelName attr_name:attr_type attr_name:attr_type ...` Models are created with singular name. Unlike controllers, created with plural. ---- # Demo Let's create a `Student` model together! `rails generate model Student name:string year:integer major:string` _don't forget_ `rails db:migrate` (we'll talk about this later) ---- # Demo Let's take a look inside `db/schema.rb`! ---- # Demo In `rails console`: ``` irb(main):001:0> Student.new(name: "", year: 2021, major: "") ``` We get back an instance of a Student. ---- # Demo Hit the up arrow and append `.save`! ``` irb(main):002:0> Student.new(name: "", year: 2021, major: "").save ``` We get back `true`. ---- # Demo Now we can get this record back from the database: ```ruby irb(main):003:0> Student.first ``` ---- # Demo Create a couple more models in your database... with different names and years! ---- # Demo ```ruby irb(main):006:0> Student.where(year: 2) ``` ---- # Laptops down! We'll now look at how we can use these in forms. --- # Relational Modeling ---- # Modeling - Rails allows you to specify structured database records - These records can have _relations_ to other records ---- # Relations - **One to one**: A `User` might have one `Profile` (with more information) - **One to many**: A `Customer` might have many `Purchase`s. - **Many to many**: A `Friend` might have many `Friend`s, and vice versa. ---- ![](https://i.imgur.com/1ST6tAO.png) ---- # Schema design exercise How would you represent Slack? ---- # Lab! ---- # Rails folder structure * `app`: Most of your application lives here! * `app/models`: Defining your Rails models and their behavior (importantly, *not* their structure) * `app/views`: Templates - where you wrote most of your Weather app last time * `app/controllers`: Classes that define how we answer to routes ---- # Rails folder structure * `config`: Configuration for how your Rails app runs * `config/routes.rb`: Defines how requests get routed to controllers! ---- # Rails folder structure * `db`: Database-specific files * `schema.rb`: Defines how the **fields** of your models are structured * `seeds.rb`: Prepares test models for your database, called with `rails db:seed` * `migrations/*.rb`: Shows how your database has changed over time - we'll talk about this more later! ---- # Relational modeling ---- # Relations in Active Record ```ruby class Student < ActiveRecord::Base has_many :assignments end ``` ---- # More Active Record Features ```ruby class Person < ActiveRecord::Base validates :username, presence: true validates :password, confirmation: true end ``` ---- # Extending Active Record ```ruby class Post < ActiveRecord::Base has_many :votes def score upvotes = votes.where(type: "up").count downvotes = votes.where(type: "down").count upvotes - downvotes end end ``` ----

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully