You are on page 1of 6
BASIC ROUTING OPTIONAL PARAMETERS REDIRECTION NAMED ROUTES RACK ROUTING CONSTRAINTS LEGACY ROUTE SCOPE RAILS 3 @ ROUTING API NESTED ROUTES YourApp: Application. routes.draw do esources :posts fateh "/all' => ‘posts#index' oot sto => "honebindex* end! natch */posts(/:yy(/:am))" => "poststindex” class Postscontrolter < Applicationcontrotter ‘def index # parans{¥y] parans (mn) end atch */sign_cut* fateh */users/nane’ natch */googte" redirect(*/signout") redirect {jparans| "/e{paranstsnane]}"> redirect ‘http://go0gle-com") namespace :api do Manespace ‘internal do Tesources accounts ¢o rember 6 get :sumary ost suspend ent post :contirn, ion => :menber Eoilection 30 get :pending end get :blocked, end on => collection + Gives you sign in_path helper a get */netto® Get ‘rack endpoint get */rack-ap" proc {Jenv| 200, (2, *Hetto Rack"I> PostsControtler-action(:index) CustomRackape mmateh */:year* posterindex, year => Adta)/, constraints shost = /locathost/) do constraints IpRestrictor get “adnin/accounts" => "queenbeetaccounts end atch */:controtler(/:action(/:id(.:format)))" = Ap => /192\,168\.1\.\441,3)/ Gives reset password path'key’) Responds to selfimatches?(request) [~ ‘Commented out by default scope *:token', token = wish do resources Foon do Tesourees incetings end end scope *(:tocate)", Fesources. :posts Foot sto => "poststindex’ locate = /en|p/ do —— Requires token parameter to get to resources and must be § alphanumeric characters [— Locale is optional for these routes sina 1S RAILS 3 BUNDLER BUNDLER $ bundle $ bundle show [gen_nane] COMMANDS | Sicsicctiteytereraalie goinlthon epancenc igor gen, owe wheel sda < > requied $ bundle —-without { Teptonal ] reas eveything exept geme incade in (Opens the gem source inthe deft eo. $ bundle ~—deploynent olates al gems ito vendo/ound, raques upto date $ bundle update [gen_nane] Gemfle lac use gem in vendorcache fay exit. Recrentes Gemleck nd une bunde”t instal new dependencies $ bundle check $ bundle package Checks ifthe dependencies tinted in Gee Copies all roject gems to vendr/ache/—use tif you dont Sr ssienedby curently ntl gem ‘nan rayon estar errs er depoymant GEMFILE source "nttp://rubygens.org” ‘Additional parameters SYNTAX gen “hpricot”, "0.6 gen : sqlites" en /Sites/local_gen” gen git: /githud.con/rails/rasts.git™ git “git://qithu.com/rails/ratis.git" do gen "raitties" gem “active _nadet" end Creating a gemset for your app Near: a eee 3 fim Senet ace ne sroup :test do 5 Nee eres caterer ieee) WORKFLOW | peveloping a new application 1. § cd new_260/ 2 $ Sinden anie sr 2. Aad pfs doped 4 Chee cae rd Gerelck into Ves After adding or removing dependencies from Gemfile 1. § bundte 2 Commit Gemfile and Gemfelock After modifying existing dependency versions 1. § bundle update 2. Commit Gentile and Gemflelock Deploying your application $ bundle package * locally § bundle # server installs ge fom vendor/cache -no extemal seer communication. For more info, visit htp//gembundlercom envylabs wi RAILS 3 @ ACTIVERELATION LAZY LOADING posts = Post.order(parans|:order]) @published "= posts.where(:published => true) Gunpublished = posts.where( :published => false) CRUD METHODS sports_posts = Post.where(:categary => ‘sports") hne«_sports_post ‘new_sports_post. plished => false) true sports_posts.update_al sports_posts.exists? # CHAINING Gjoe_posts = Post.where(:authar => “Joe").includes(: comments). Limit (10) Foxes query execution ond (NAMED) SCOPES — ctass post = activenecors::tase retus an ary, not elation default_scope order('titie') ‘scope :published, where(:published => true) ‘scope iunpublished, where(:published => false) end DEPRECATED find(ad-or-orray-of-ids, options) su opoon - find(:first, options options are now se fFind(zatt, options) Using the chain methods tirst(options) alt(options) Update_alU(updates, conditions, options) Produced by envylabs XSS PROTECTION UNOBTRUSIVEJS HTMLS CUSTOM DATAATTRIBUTES sew-sevos DEPRECATED USING JQUERY RAILS 3 @ YSS PROTECTION & WS <= Qpost.body % ——> safe by default unsafe t= Link to raw(" not escaped escaped not escaped > true de form for(gpost, sremote => true) do |f| % nethod => idelete = = Link to ‘Destroy’, epost, Gata-renote —_data-confirm y-disable-with Go to https/fjthub comyralsjquery-us for instructions Produced by envylabs ® Atti RAILS 3 RGA RAILS MAIL GENERATOR BASIC MAILER SYNTAX DELIVERING MESSAGES DEFAULTS AND ATTACHMENTS RESPOND_ TO AND RESPOND_ WITH rails generate mailer Usertlailer welcone forgot_password — Creates: class Userlailer < ActionHailer: :Base apprncws/ser abril def welcone(user, subdomain) soph aewshee sae user = user (subdomain = Subdomain a7 5 mail(: from => ‘admingapp.con ese instance variables are tom euserrensity dvalable within your view subject => ‘Welcone*) end end Usertlailer.welcone(user, subdonain) deliver message = UserMailer.welcone(user, subdonain) nnessage.deLiver class Usertailer < ActionMailer: #1 default :fron => ‘admingtest. con ply_to => ‘noreply@test. com “Timé-Code" => Tine,now.to_i.to_s ees eae) fst easter cocoa stiscments[‘testrpat']_ = File-read{ Rails. root oin( ‘public/test.pdf")) attachments['photo.jpg'] = { :content => generate_image() maill:to evseicers subject => ‘Welcome to TestApp') do | format] ae ecae eters ta Rent el xt { render “otheratextowetcme’ }) Deets Tes class UsersControtler < ApplicationControtler Fespond_to :html, :json, only => :index respond to :xml,” :except => :index def index respond_with(@users = User.all, :status => + end def create ‘user = User. create(params{:user]) respond withi@user) do |fornat| fornat.html { redirect_to(users_path) } end end end envylabs wi “ACTIVEMODEL RAILS 3 DIRTY VALIDATIONS SERIALIZATION CALLBACKS class Person include ActiveModel::Dirty define attribute methods [:nanel det name ‘@nane end def nane=(val) rnane_wil_change! @nane = val end def save @previously_changed = changes @changed_attributes.clear end end class Person Include Activetodel: :Validations attraccessor :enail validates presence_of :enail end = Person.new Person: 0x000002021071 Lid? peerrors > Cenai ‘can't be blank"1} class Person Include Activetlodel: :Serializers: attraccessor :name det attributes {sname => name} end end class Person extend ActiveModel::CaLtbacks define model_cal backs :save before_save faction before save def save —run_save_callbacks do # Your save action methods here end end private def action_before_save end end >> person = Person.find{ id) 3> person. changed? = fatce >> person.nane = ‘Bob! 35 person. changed? >> person.nane_changed? >> person.nane_was >> person.nane_change = T'unele Bob", "B0b') >> person.nane = ‘Bitl' > person. nane_change TUnete Bob", "BILL Shortcuts validates :torms, sacceptance => true Validates password, confirmation => true Validates Husernane, :exclusia validates :enail, :fornat swith => AUST 0 create } age, tnclusio validates MODULES Attributeethods Cattbacks: birty Errors Naming Observing Serialization Validations Cain's sw(adain) 2-20-9] \.) +1a-21{2,)1\2/i, sn 0.9) validates :first-none,.slength => { snaxinun => 30 } validates :2ge, inunericality validates ‘username, ‘presence => trve mniqueness => rue validates :usernane, >> p = Person.new > R> ponane = "Grego" Gregg) > p.to_ison Grega\"} sina 1S

You might also like