Handouts Slides Basic Rails

Embed Size (px)

Citation preview

  • 7/27/2019 Handouts Slides Basic Rails

    1/25

    CS169.1x Lecture 6:

    Basic Rails"Fall 2012"

    1"

  • 7/27/2019 Handouts Slides Basic Rails

    2/25

    The Database is Golden

    Contains valuable customer datadont wantto test your app on that!

    Rails solution: development, production andtest environments each have own DBDifferent DB types appropriate for eachHow to make changes to DB, since will haveto repeat changes on production DB?Rails solution: migrationscript describingchanges, portable across DB types

  • 7/27/2019 Handouts Slides Basic Rails

    3/25

    Migration Advantages

    Can identify each migration, and know whichone(s) applied and when

    Many migrations can be created to be reversibleCan manage with version controlAutomated == reliably repeatableCompare: use Bundler vs. manuallyinstall libraries/gemsTheme: dont do itautomate itspecifywhat to do, create tools to automate

  • 7/27/2019 Handouts Slides Basic Rails

    4/25

    Meet a Code Generator

    rails generate migration CreateMovies

    Note, this just creates themigration. We havent appliedit.

    Apply migration to development:rakedb:migrate

    Apply migration to production:heroku rakedb:migrateApplying migration also records in DB itselfwhich migrations have been applied

    http://pastebin.com/

    VYwbc5fq

  • 7/27/2019 Handouts Slides Basic Rails

    5/25

    Rails Cookery #1

    Augmenting app functionality ==adding models, views, controller actions

    To add a new modelto a Rails app:

    (or change/add attributes of an existing model)

    1.Create a migration describing the changes:rails generate migration(gives you boilerplate)

    2.Apply the migration: rake db:migrate3.If new model, create model file app/models/model.rbUpdate test DB schema: rake db:test:prepare

  • 7/27/2019 Handouts Slides Basic Rails

    6/25

    An object representing an instance of a model

    An object representing a table

    Come on, it could be anything

    An object representing a database

    *

    Based on what youve seen of Rails, what kind of object is likelybeingyielded in the migration code:def up

    create_table 'movies' do |t|t.datetime 'release_date' ...

    endend

  • 7/27/2019 Handouts Slides Basic Rails

    7/25

    Ted Codd

    CRUD in SQL

    Structured Query Language (SQL) is thequery language used by RDBMSsRails generates SQL statements atruntime, based on your Ruby code

    4 basic operations on a table row:Create, Read, Update attributes, DeleteINSERT INTO users(username, email, birthdate)VALUES ("fox","[email protected]", "1968-05-12"),

    "patterson", "[email protected]", "????")

    SELECT * FROMusersWHERE (birthdate BETWEEN "1987-01-01" AND2000-01-01)

    UPDATE users SET email = "[email protected]"WHEREusername="fox"

    DELETE FROMusersWHERE id=1

  • 7/27/2019 Handouts Slides Basic Rails

    8/25

    The Ruby side of a model

    Subclassing fromActiveRecord::Baseconnects a model to the databaseprovides CRUD operations on the modelDatabase table name derived frommodels name: Moviemovies

    Database table column names are getters &setters for model attributes

    Observe: the getters and setters do notsimply modify instance variables!

    http://pastebin.com/ruu5y0D8

  • 7/27/2019 Handouts Slides Basic Rails

    9/25

    Creating: new save

    Must call save orsave! on an AR modelinstance to actually save changes to DB

    '!' version is dangerous: throws exception ifoperation failscreate just combines new and saveOnce created, object acquires a primary key(id column in every AR model table)ifx.id is nil orx.new_record? is true, x has neverbeen saved

    These behaviors inherited fromActiveRecord::Basenot true of Ruby objects in general

  • 7/27/2019 Handouts Slides Basic Rails

    10/25

    Read: finding things in DB

    class method whereselects objects based onattributesMovie.where("rating='PG'")

    Movie.where('release_date < :cutoffand

    rating = :rating',

    :rating => 'PG', :cutoff=> 1.year.ago)Movie.where("rating=#{rating}") # BAD IDEA!

    Can be chained together efficientlykiddie = Movie.where("rating='G'")

    old_kids_films =

    kiddie.where "release_date < ?", 30.years.ago

  • 7/27/2019 Handouts Slides Basic Rails

    11/25

    Read: find_*

    find by id:Movie.find(3) #exception if notfoundMovie.find_by_id(3)# nil if not found

    dynamic attribute-based finders usingmethod_missing:Movie.find_all_by_rating('PG')

    Movie.find_by_rating('PG')Movie.find_by_rating!('PG')

  • 7/27/2019 Handouts Slides Basic Rails

    12/25

    Update: 2 ways

    Modify attributes, then saveobjectm=Movie.find_by_title('The Help')m.release_date='2011-Aug-10'

    m.save!Update attributes on existingobjectMovie.find_by_title('The Help').update_attributes!(

    :release_date => '2011-Aug-10')

    Transactional: either all attributes areupdated, or none are

  • 7/27/2019 Handouts Slides Basic Rails

    13/25

    def silly_fortune_2

    self.fortune_text + 'in bed'

    end

    def silly_fortune_3

    fortune_text + 'in bed'

    end

    They will all return a silly fortune

    def silly_fortune_1

    @fortune_text + 'in bed'

    end

    *

    Assume table fortune_cookieshas column fortune_text

    Which of these instance methods ofFortuneCookie "show", :controller=>"movies"}

    params[:id]3

    def show@movie =

    Movie.find(params[:id])

    end

  • 7/27/2019 Handouts Slides Basic Rails

    17/25

    What else can we do?

    How about letting user return to movie list?RESTful URI helper to the rescue again:movies_path with no arguments links to Indexaction=link_to 'Back to List', movies_path

  • 7/27/2019 Handouts Slides Basic Rails

    18/25

    Only (C) is true

    Only (A) and (B) are true

    Only (A) and (C) are true

    Only (A) is true

    *

    A) A route consists ofboth a URI and an HTTP method

    B) A route URI must be generated by Rails URI helpers

    C) A route URI may be generated by Rails URI helpers

  • 7/27/2019 Handouts Slides Basic Rails

    19/25

    Dealing with forms

    Creating a resource usuallytakes 2 interactions

    new: Retrieve blank formcreate: Submit filled formHow to generate/display?How to get values filled inby user?What to return (render)?

  • 7/27/2019 Handouts Slides Basic Rails

    20/25

    Rails Cookery #3

    To create a new submittable form:1.Identify the action that gets the form itself2.Identify the action that receives submission3.Create routes, actions, views for eachIn form view, form element name attributescontrol how values will appear in params[]

    Helpers provided for many common elements

  • 7/27/2019 Handouts Slides Basic Rails

    21/25

    Creating the Form

    Anatomy of a form in HTMLthe action and methodattributes (i.e., the route)only namedform inputs will be submittedGenerating the form in Railsoften can use URI helper foraction, since its justthe URI part of a route (still need method)

    form field helpers (see api.rubyonrails.org) generateconveniently-named form inputs

    http://pastebin.com/

    k8Y49EhE

    http://pastebin.com/

    3dGWsSq8

  • 7/27/2019 Handouts Slides Basic Rails

    22/25

    Redirection, the Flash and the

    Session(ELLS 4.7)

    Armando Fox

    2012 Armando Fox & David Patterson

    Licensed under

    Creative Commons Attribution-

    NonCommercial-ShareAlike 3.0 Unported

    What view should be rendered

  • 7/27/2019 Handouts Slides Basic Rails

    23/25

    What view should be rendered

    for create action?

    Idiom: redirectuser to a more useful page.e.g., list of movies, if create successfule.g., New Movie form, if unsuccessfulRedirect triggers a whole new HTTPrequestHow to inform userwhythey were redirected?Solution: flash[]quacks like a hash that

    persists until end ofnextrequestflash[:notice] conventionally for informationflash[:warning] conventionally for errors

  • 7/27/2019 Handouts Slides Basic Rails

    24/25

    Flash & Session

    session[]: like a hash that persists foreverreset_sessionnukes the whole thingsession.delete(:some_key), like a hashBy default, cookies store entire contents ofsession & flash

    Alternative: store sessions in DB table (Google railssession use database table)Another alternative: store sessions in a NoSQLstorage system, like memcached

  • 7/27/2019 Handouts Slides Basic Rails

    25/25

    Truebut a bad idea!

    False, because you cant put arbitrary

    objects into a hashFalse, because session[] isnt really ahash, it just quacks like one

    Trueknock yourself out!

    *

    Ben Bitdiddle says: You can put arbitraryobjects (not just simple ones like ints and

    strings) into the session[]. What do youthink?