Migrations

2y ago
10 Views
2 Downloads
245.39 KB
10 Pages
Last View : 14d ago
Last Download : 3m ago
Upload by : Grant Gall
Transcription

Migrations1 of 10To Create a Blank Migration: rails g migration name To Add Columns: rails g migration Add Anything To TableName [columnName:type]To Remove Columns: rails g migration Remove Anything From TableName [columnName:type]Column tion Methods* value 30falsetrue:emailtruecreate tabledrop tablechange columnremove columnremove indexchange tableadd columnrename columnadd indexActive Record Supported Types:primary :decimal:timestamp:date:boolean* See documentation for syntaxRemove ColumnAdd Columnrails g migration RemoveAgeFromZombies age:integerrails g migration AddEmailToZombies email:stringclass RemoveAgeFromZombies ActiveRecord::Migrationdef upremove column :zombies, :ageenddef downadd column :zombies, :age, :integerendendclass AddEmailToZombies ActiveRecord::Migrationdef upadd column :zombies, :email, :stringenddef downremove column :zombies, :emailendendCreate Tablerails g migration CreateZombiesTable name:string, bio:text, age:integerclass CreateZombiesTable ActiveRecord::Migrationdef upcreate table :zombies do t t.string :namet.text :biot.integer :aget.timestampsendendDon’t Forget to Rake! rake db:migrateRun all missing migrations rake db:rollbackRollback the previous migration rake db:setupCreate db, load schema & seed rake db:schema:dumpDump the current db statedb/schema.rbdef downdrop table org/migrations.html

Rails Command LineCommandShortcut2 of 10Descriptionrails new app name # creates a new Rails applicationrails serverrails s# starts up the Rails serverrails generaterails g# generates template coderails consolerails c# starts up the Rails consolerails dbconsolerails db# starts up the Rails db consoleHelp:All commands can be run with -hfor more informationGenerate Examplesrails g scaffold zombie name:string bio:text age:integerrails g migration RemoveEmailFromUser email:stringrails g mailer ZombieMailer decomp change lost brainModelsNamed ScopeExamplesclass Zombie ActiveRecord::Basescope :rotting, where(rotting: true)scope :fresh, where(“age 20”)scope :recent, order(“created at desc”).limit(3)endCallbacksbefore validationbefore savebefore createbefore updatebefore ie.rotting.recentExamplesafter validationafter saveafter createafter updateafter destroyafter create :send welcome emailbefore save :encrypt passwordbefore destroy :set deleted flagafter update { zombie logger.info “Zombie #{zombie.id} updated” }Self ScopeReading attributes does not require “self ” but settingattributes does require “self ”class Zombie ActiveRecord::Basebefore save :make rottingdef make rottingif age 20self.rotting trueendendendRelationship Optionsdependent: :destroyforeign key: :undead idprimary key: :zidvalidate: trueRelational Includes Examples*@zombies Zombie.includes(:brain).all@recent Zombie.recent.includes(:brain)* To avoid extra queries

REST & RoutesRake Routes3 of 10Generates rake routeszombies- Prints your RESTful routesnew zombieedit zombiezombieGET /zombiesPOST /zombiesGET /zombies/newGET /zombies/:id/editGET /zombies/:idPUT /zombies/:idDELETE /zombies/:idExample Link To Usage % % % % % % link tolink tolink tolink tolink tolink to'All Zombies', zombies path % 'New Zombie', new zombie path % 'Edit Zombie', edit zombie path(@zombie) % 'Show Zombie', zombie path(@zombie) % 'Show Zombie', @zombie % 'Delete Zombie', @zombie, method :delete % {:action ”index”, :controller ”zombies”}{:action ”create”, :controller ”zombies”}{:action ”new”, :controller ”zombies”}{:action ”edit”, :controller ”zombies”}{:action ”show”, :controller ”zombies”}{:action ”update”, :controller ”zombies”}{:action ”destroy”, :controller ”zombies”}Relative Pathszombies pathnew zombie pathAbsolute Pathszombies urlnew zombie urlPath Generated/zombies/zombies/newURL host:3000/zombies/newFormsExample % form for(@zombie) do f % % f.text field :name % % f.text area :bio % % f.select :decomp, ['fresh', 'rotting', 'stale'] % % f.select :decomp, [['fresh', 1], ['rotting', 2], ['stale', 3]] % % f.radio button :decomp, 'fresh', checked: true % % f.radio button :decomp, 'rotting' % % f.radio button :decomp, 'stale' % % f.check box :rotting % % f.submit % % end % Alternate Text Input Helpers % % % % % % f.password field :password % f.number field :price % f.range field :quantity % f.email field :email % f.url field :website % f.telephone field :mobile %

Nested ts controller.rb4 of 10TwitterForZombies::Application.routes.draw doresources :zombies doresources :tweetsendendclass TweetsController ApplicationControllerbefore filter :get zombiedef get zombie@zombie Zombie.find(params[:zombie id])enddef show@tweet ts/2params { :zombie id 4, :id 2 }def create@tweet @zombie.tweets.new(params[:tweet])if @tweet.saveredirect to [@zombie, @tweet]elserender action: “new”enddef index@tweets @zombie.tweetsendend34/zombies/4/tweetsparams { :zombie id 4 }app/views/tweets/ form.html.erb % form for([@zombie, @tweet]) do f % app/views/tweets/index.html.erb % @tweets.each do tweet % tr td % tweet.body % /td td % link to ‘Show’, [@zombie, tweet] % /td td % link to ‘Edit’, edit zombie tweet path(@zombie, tweet) % /td td % link to ‘Destroy’, [@zombie, tweet], method: :delete % /td /tr % end % % link to ‘New Tweet’, new zombie tweet path(@zombie) % Look Up URL Helpers rake routes

View Partials & View Helpers5 of 10app/views/tweets/new.html.erb h1 New tweet /h1 % render 'form' % % link to 'Back', zombie tweets path(@zombie) % app/views/tweets/ form.html.erb h1 New tweet /h1 % render 'form' % % link to 'Back', zombie tweets path(@zombie) % app/views/tweets/edit.html.erb h1 Editing tweet /h1 % render 'form' % - Partials start with an underscoreView Helper div id "tweet % tweet.id % " class "tweet" % tweet.body % /div Same As % div for tweet do % % tweet.body % % end % View Helper % @zombies.each do zombie % % render zombie % % end % Same As % render @zombies % Additional HelpersCallsdom id(@tweet)- #tweet 2Looks Forviews/zombies/ zombie.html.erbResult % truncate("I need brains!", :length 10) % I need bra % truncate("I need brains!", :length 10, :separator ' ') % I need I see % pluralize(Zombie.count, "zombie") % I see 2 zombies / I see 1 zombieHis name was % @zombie.name.titleize % His name was Ash WilliamsAsh’s zombie roles are % @role names.to sentence % Ash’s zombie roles are Captain, and Solidier.He was buried alive % time ago in words @zombie.created at % agoHe was buried alive 2 days agoPrice is % number to currency 13.5 % Price is 13.50Ash is % number to human 13234355423 % years old % Ash is 13.2 billion years old

Creating a Mailer6 of 10Generator: rails g mailer ZombieMailer decomp change lost brainMailer Class Example -app/mailers/zombie mailer.rbclass ZombieMailer ActionMailer::Basedefault from: "from@example.com"def decomp change(zombie)@zombie zombie@last tweet @zombie.tweets.lastattachments['z.pdf'] File.read("#{Rails.root}/public/zombie.pdf")mail to: @zombie.email, subject: 'Your decomp stage has changed'endendMailer Text Views -app/views/zombie mailer/decomp change.text.erbfrom: my@email.comcc: my@email.combcc: my@email.comreply to: my@email.comMass Mailing Notes:Mass mailing is best done outside ofRails. You can use gems for serviceslike MadMimi.com if you plan onsending a lot of nmailer basics.htmlGreetings % @zombie.name % Mailer HTML Views -Additional Optionsapp/views/zombie mailer/decomp change.html.erb h1 Greetings % @zombie.name % /h1 Sending Mail -app/models/zombie.rbZombieMailer.decomp change(@zombie).deliverAssets & Asset PathsAsset Tag Helpers % javascript include tag "custom" % % stylesheet link tag "style" % % image tag "rails.png" % Asset Paths in Stylesheets -app/assets/stylesheets/zombie.css.erbform.new zombie input.submit {background-image: url( % asset path('button.png') % );}Using SASS, CoffeeScript AssetsTo compile with other CSS/JS helpers, just add the necessary coffee-script/

CoffeeScript & jQueryJavaScript & jQueryapp/assets/javascripts/zombie.js (document).ready(function() { ('#show-bio').click(function(event) {event.preventDefault(); (this).hide(); ('.field#bio').show();}}7 of 10CoffeeScript & jQueryapp/assets/javascripts/zombie.js.coffee (document).ready - ('#show-bio').click (event) - event.preventDefault() (this).hide() ('.field#bio').show()CoffeeScript AJAX Example (document).ready - ('div#custom phase2 form').submit (event) - event.preventDefault()url (this).attr('action')custom decomp ('div#custom phase2 #zombie decomp').val() .ajaxtype: 'put'url: urldata: { zombie: { decomp: custom decomp } }dataType: 'json'success: (json) - ('#decomp').text(json.decomp).effect('highlight') ('div#custom phase2').fadeOut() if json.decomp "Dead (again)"SASS & /assets/stylesheets/zombie.css.scss.erbform.new zombie {border: 1px dashed gray;}form.new zombie {border: 1px dashed gray;.field#bio {display: none;}form.new zombie .field#bio {display: none;}input.submit {form.new zombie input.submit {background-image: url( % asset path('button.png') % );}background-image: url( % asset path('button.png') % );}}To Remove SASS/CoffeeScript Default Asset GenerationGemfileRemovegem 'sass-rails'gem 'coffee-script'then rerun 'bundle install'

Sprockets & ion.jsContains a manifest of the JavaScript files we use// require jquery// require jquery ujsLooks for jquery.js in all asset paths// require sharedLoads: lib/assets/javascripts/shared.js.coffee// require tree .app/assets/stylesheet/application.cssContains a manifest of the stylesheets we use/** require reset* require self* require tree .*/Styles in this file are included after the reset stylesheetform.new zombie {border: 1px dashed gray;}Rendering / HTTP Status CodesResponds to Exampleapp/controllers/zombies controller.rbclass ZombiesController ApplicationControllerdef show@zombie Zombie.find(params[:id])respond to do format format.html doif @zombie.decomp 'Dead (again)'render :dead againendendformat.json { render json: @zombie }endendendHTTP Status Codes200 :ok201 :created422 :unprocessed entityRenders app/views/zombies/dead again.html.erbRenders app/views/zombies/show.html.erbRenders JSONJSON Rendering Examples401 :unauthorized102 :processing404 :not foundrender json: @zombie.errors, status: :unprocessable entityrender json: @zombie, status: :created, location: @zombie8 of 10

Custom RoutesTypes:member9 of 10RouteURLget :decomp, on: :member/zombies/:id/decompput :decay, on: :member/zombies/:id/decayget :fresh, on: :collection/zombies/freshpost :search, on: :collection/zombies/searchacts on a single resource:collectionacts on a collection of resourcesExamples % % % % link to 'Fresh zombies', fresh zombies path % form tag(search zombies path) do f % link to 'Get decomp', decomp zombie path(@zombie) % form for @zombie, url: decay zombie path(@zombie) % Custom JSON ResponsesExamples@zombie.to json(only: :name)@zombie.to json(except: [:created at, :updated at, :id, :email, :bio]){ “name” : “Eric” }{ "age":25, "decomp":"Fresh", "name":"Eric", "rotting":false }@zombie.to json(only: [:name, :age])@zombie.to json(include: :brain, except: [:created at, :updated at, :id]){ “name” : “Eric”, "age": 25 }{"age":25,"bio":"I am ,"name":"Eric","rotting":false,"brain": { "flavor":"Butter", "status":"Smashed", "zombie id":3 }}

AJAX110 of 10Make a Remote Link or Form Call % link to 'delete', zombie, method: :delete, remote: true % a href "/zombies/5" data-method "delete" data-remote "true" rel "nofollow" delete /a % form for (@zombie, remote: true) do f % form action "/zombies" data-remote "true" method "post" 2Ensure the Controller Can Accept JavaScript Calls3Write the JavaScript to Return to the Clientrespond to do format format.jsendapp/views/zombies/ action name .js.erb ('# % dom id(@zombie) % ').fadeOut();Other jQuery Actions (' selector ').append( content or jQuery object ); (' selector ').effect('highlight'); (' selector ').text( string );Requires jQuery UI

rails dbconsole rails db # starts up the Rails db console Command Shortcut Description Help: All commands can be run with -h for more information rails g scaffold zombie name:string bio:text age:integer rails g migration RemoveEmailFromUser email:string rails g mailer Zombi

Related Documents:

Migrations in the German Lands: An Introduction ALEXANDER SCHUNKA Overview T he history of human cultures is a history of migrations and movements.1 The contours of human mobility are remarkably sensitive to a broader historical context, and migrations have to a

Le glossaire du Réseau Européen des Migrations (REM), constitué de termes touchant à l’asile et aux migrations, essentiellement issus de l’Acquis de l’UE, vise notamment à améliorer la comparabilité entre les États membres, par le biais de l’utilisation et de la compréhension commune des termes et des définitions qu’il contient.

sades). Eventually the empire succumbed to Muslim conquest in 1453. The later Byzantine emperors faced new enemies in the north and south. Following the wave of Germanic migrations (see Chapter 5), Slavic and Turkic peoples appeared on the north-ern frontiers as part of centuries-long and poorly understood population migrations in Eurasian

Les migrations circulaires et temporaires sont devenues des concepts importants au niveau mondial et au niveau de l'UE et ont fait l'objet d'un intérêt remarquable parmi les décideurs politiques et les chercheurs, notamment en rapport avec la question plus vaste de la migration et du développement.

RAPPORT STATISTIQUE ANNUEL SUR LA MIGRATION ET LA PROTECTION INTERNATIONALE Année de référence : 2009 Etude élaborée par le Point de contact français du Réseau européen des migrations (REM) Le Réseau Européen des Migrations a été institué par la décision du Conseil 2008/381/CE et est soutenu financièrement par l’Union Européenne.

One sixteenth-century German explorer seems to have originated . such as the early eighteenth-century migrations of the Tupi-Guaranis witnessed by the French in the Guianas (Metraux 1927; Hurault 1972). . and the eventual colonization of the appropriated

MIGRATIONS PRIOR TO GEORGIA, TOMOCHICHI AS AN EXAMPLE Native Migrations . German Lutheran George II, 1734 Ebenezer Other German Protestants too . lands Vagabond/ debt laws Settlers from Georgia and oth

the map of migrations in the chapter “Celtic Origins” he shows an arrow from the proto - Celtic territory circa 1000 BC heading north to the tip of the Jutland Peninsula and labels this, “Slav – German Migrations