SlideShare a Scribd company logo
Intro to Ruby on Rails by Mark Menard Vita Rara, Inc.
Ruby © Vita Rara, Inc. “ I always knew one day Smalltalk would replace Java. I just didn’t know it would be called Ruby.” - Kent Beck,  Creator of “Extreme Programming”
Ruby on Rails Ruby on Rails is astounding. Using it is like watching a kung-fu movie, where a dozen bad-ass frameworks prepare to beat up the little newcomer only to be handed their asses in a variety of imaginative ways.  -Nathan Torkington,    O'Reilly Program Chair for OSCON   © Vita Rara, Inc.
The Elevator Pitch Ruby on Rails is an open-source web framework that is optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration. © Vita Rara, Inc.
Overview Rails is a full stack web framework Model: ActiveRecord ORM database connectivity Database schema management View: ActiveView View layer Templates Controller: ActionController Web controller framework Manages web integration Active Support Extensions to Ruby to support web development Integrated Ajax support © Vita Rara, Inc.
The Rails Philosophy Ruby - less and more readable code, shorter development times, simple but powerful, no compilation cycle. Convention over configuration Predefined directory structure, and naming conventions Best practices: MVC, DRY, Testing Almost everything in Rails is Ruby code (SQL and JavaScript are abstracted) Integrated AJAX support. Web services with REST. Good community, tools, and documentation Extracted from a real application: Basecamp © Vita Rara, Inc.
Rake: The Ruby Make Rake lets you define a dependency tree of tasks to be executed. Rake tasks are loaded from the file Rakefile Rake automates and simplifies creating and managing the development of a Rails project. © Vita Rara, Inc.
Environments Rails has support for multiple execution environments. Environments encapsulate database settings and other configuration. Typical environments Development Test Production Additional environments are easy to add. © Vita Rara, Inc.
Migrations Managing Schema Evolution
Managing Data Schemas Rails includes support for migrations to manage the evolution of your database schema. No need to write SQL.  Migrations use a database independent Ruby API. Migrations are Ruby scripts giving you access to the full power of the language. © Vita Rara, Inc.
Migrations Typical migration functions: create_table add_column change_column rename_column rename_table add_index © Vita Rara, Inc.
Migration Example © Vita Rara, Inc. create_table  "users" , :force => true  do  |t|  t.string :login, :email, :remember_token  t.string :salt, :crypted_password, :limit =>  40   t.timestamps  t.datetime :remember_token_expires_at  end
ActiveRecord Modeling the World
Fundamentals One database table maps to one Ruby class Table names are plural and class names are singular Database columns map to attributes, i.e. get and set methods, in the model class All tables have an integer primary key called id Database tables are created with migrations   © Vita Rara, Inc.
ActiveRecord Model Example © Vita Rara, Inc. create_table  &quot;persons&quot;   do  |t|  t.string :first_name, last_name t.timestamps  end class  Person < ActiveRecord::Base end p = Person.new p.first_name = ‘Mark’ p.last_name = ‘Menard’ p.save
CRUD Create: create, new Read: find, find_by_<attribute> Update: save, update_attributes Delete: destroy © Vita Rara, Inc.
Finding Models User.find(:first) User.find(:all) User.find(1) User.find_by_login(‘mark’) User.find(:all, :conditions => [ “login = ? AND password = ?”, login, password]) © Vita Rara, Inc.
Advanced Finding Finders also support: :limit :offset :order :joins :select :group © Vita Rara, Inc.
Update user = User.find(1) user.first_name = ‘Mark’ user.last_name = ‘Menard’ user.save! © Vita Rara, Inc.
Transactions Account.transaction do account1.deposit(100) account2.withdraw(100) end © Vita Rara, Inc.
ActiveRecord Associations Joining Things Together
ActiveRecord Associations Two primary types of associations: belongs_to has_one / has_many There are others, but they are not commonly used. © Vita Rara, Inc.
ActiveRecord Associations © Vita Rara, Inc. # Has Many class  Order < ActiveRecord::Base has_many :order_line_items end class  OrderLineItem < ActiveRecord::Base belongs_to :order end # Has One class  Party < ActiveRecord::Base has_one :login_credential end class  LoginCredential < ActiveRecord::Base belongs_to :party end
Association Methods Associations add methods to the class. This is an excellent example of meta-programming. Added methods allow easy management of the associated models. order.order_line_items << line_item order.order_line_items.create() © Vita Rara, Inc.
ActiveRecord Validations Keeping Your Data Safe
Validation Validations are rules in your model objects to help protect the integrity of your data Validation is invoked by the save method. Save returns true if validations pass and false otherwise. If you invoke save! then a RecordInvalid exception is raised if the object is not valid Use save(false) if you need to turn off validation  © Vita Rara, Inc.
Validation Callback Methods validate validate_on_create validate_on_update © Vita Rara, Inc.
Validation Example © Vita Rara, Inc. class  Person < ActiveRecord::Base  def   validate   puts “validate invoked”  end   def   validate_on_create   puts “validate_on_create invoked”  end   def   validate_on_update   puts “validate_on_update invoked”  end   end   peter  =  Person.create(:name => “Peter”) # => validate, validate_on_create invoked  peter.last_name  =  “Forsberg”  peter.save # => validate_on_update invoked
Validation Macros validates_acceptance_of  validate_associated  validates_confirmation_of validates_each  validates_exclusion_of  validates_format_of  validates_inclusion_of  validates_length_of  validates_numericality_of  validates_presence_of  validates_size_of  validates_uniqueness_of  © Vita Rara, Inc.
Validation Macro Example © Vita Rara, Inc. class  User < ActiveRecord::Base  validates_presence_of :name, :email, :password  validates_format_of :name, :with =>  /^ \w +$/ ,  :message => “may only contain word characters”  validates_uniqueness_of :name, :message => “is already  in  use”  validates_length_of :password, :within =>  4 .. 40   validates_confirmation_of :password  validates_inclusion_of :role, :in =>  %w(super admin user) ,  :message => “must be  super , admin,  or  user”,  :allow_nil => true  validates_presence_of :customer_id,  :if => Proc. new  { |u| %w(admin user) .include?(u.role)  }  validates_numericality_of :weight,  :only_integer => true,  :allow_nil => true  end
ActionController The “C” in MVC
Controllers Controllers are Ruby classes that live under app/ controllers Controller classes extend ActionController::Base An action is a public method and/or a corresponding view template  © Vita Rara, Inc.
Rendering a Response A response is rendered with the render command An action can only render a response once Rails invokes render automatically if you don’t Redirects are made with the redirect_to command  © Vita Rara, Inc.
A Simple Controller © Vita Rara, Inc. class  PrioritiesController < InternalController def   show @priority  =  current_account.priorities.find(params[:id]) end def   new @priority  =  Priority. new end def   create @priority  =  Priority. new (params[:priority]) if  @priority.save flash[:notice]  =   'The priority was successfully created.' redirect_to account_url else render :action =>  &quot;new&quot; end end ... end
Sessions A hash stored on the server, typically in a database table or in the file system. Keyed by the cookie _session_id Avoid storing complex Ruby objects, instead put id:s in the session and keep data in the database, i.e. use session[:user_id] rather than session[:user]   © Vita Rara, Inc.
ActionView Our Face to the World
What is ActionView? ActionView is the module in the ActionPack library that deals with rendering a response to the client. The controller decides which template and/or partial and layout to use in the response Templates use helper methods to generate links, forms, and JavaScript, and to format text.  © Vita Rara, Inc.
Where do templates live? Templates that belong to a certain controller typically live under app/view/controller_name, i.e. templates for Admin::UsersController would live under app/ views/admin/users Templates shared across controllers are put under app/views/shared. You can render them with render :template => ‘shared/my_template’ You can have templates shared across Rails applications and render them with render :file => ‘path/to/template’ © Vita Rara, Inc.
Template Environment Templates have access to the controller object’s flash, headers, logger, params, request, response, and session. Instance variables (i.e. @variable) in the controller are available in templates The current controller is available as the attribute controller.   © Vita Rara, Inc.
Embedded Ruby <%= ruby code here %> - Evaluates the Ruby code and prints the last evaluated value to the page. <% ruby code here %> - Evaluates Ruby code without outputting anything to the page. © Vita Rara, Inc.
Example View © Vita Rara, Inc. <p> <b>Name:</b> <%=h @category.name %> </p> <%= link_to  'Edit' , edit_category_path(@category) %> | <%= link_to  'Back' , categories_path %>
A Check Book Ledger Example
Basic Requirements The System should allow the management of multiple accounts The system should maintain an account ledger for every account in the system. Each account ledger should consist of ledger entries. Each ledger entry can be either a positive or negative value. Ledger entries can be associated with a payee and a category. © Vita Rara, Inc.
Implementing a Check Book Ledger Create a new project Theme the project Define our resources using:  script/generate scaffold Account Ledger Entry Payee Category Theme models Implement  © Vita Rara, Inc.
Shameless Self Promotion
Ruby and Rail Training One day to three day programs. Introduction to Ruby Advanced Ruby Introduction to Rails Advanced Rails Test Driven Development Behavior Driven Development Test Anything with Cucumber Advanced Domain Modeling with ActiveRecord Domain Driven Development with Rails © Vita Rara, Inc.
Ruby on Rails Consulting Full Life Cycle Project Development Inception Implementation Deployment Long Term Support Ruby on Rails Mentoring Get your team up to speed using Rails © Vita Rara, Inc.
Contact Information Mark Menard [email_address] http://www.vitarara.net / 518 369 7356 © Vita Rara, Inc.

More Related Content

What's hot (20)

PDF
React.js for Rails Developers
Arkency
 
PDF
React on rails v6.1 at LA Ruby, November 2016
Justin Gordon
 
PDF
RESTful Web Applications with Apache Sling
Bertrand Delacretaz
 
PDF
Introduction to Ruby on Rails
Alessandro DS
 
PDF
Web a Quebec - JS Debugging
Rami Sayar
 
PDF
An Intense Overview of the React Ecosystem
Rami Sayar
 
PPTX
Rails Engine Patterns
Andy Maleh
 
PDF
PLAT-8 Spring Web Scripts and Spring Surf
Alfresco Software
 
PPTX
API Development with Laravel
Michael Peacock
 
PPTX
Rails Engine | Modular application
mirrec
 
PPT
Build Your Own CMS with Apache Sling
Bob Paulin
 
PPTX
Rails Engine :: modularize you app
Muntasim Ahmed
 
PPTX
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Dilouar Hossain
 
PDF
AngularJS meets Rails
Elena Torró
 
PDF
How angularjs saves rails
Michael He
 
PDF
RoR 101: Session 5
Rory Gianni
 
PPTX
Laravel Eloquent ORM
Ba Thanh Huynh
 
PPTX
Laravel overview
Obinna Akunne
 
PPTX
Laravel introduction
Simon Funk
 
PPTX
Rails Request & Middlewares
Santosh Wadghule
 
React.js for Rails Developers
Arkency
 
React on rails v6.1 at LA Ruby, November 2016
Justin Gordon
 
RESTful Web Applications with Apache Sling
Bertrand Delacretaz
 
Introduction to Ruby on Rails
Alessandro DS
 
Web a Quebec - JS Debugging
Rami Sayar
 
An Intense Overview of the React Ecosystem
Rami Sayar
 
Rails Engine Patterns
Andy Maleh
 
PLAT-8 Spring Web Scripts and Spring Surf
Alfresco Software
 
API Development with Laravel
Michael Peacock
 
Rails Engine | Modular application
mirrec
 
Build Your Own CMS with Apache Sling
Bob Paulin
 
Rails Engine :: modularize you app
Muntasim Ahmed
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Dilouar Hossain
 
AngularJS meets Rails
Elena Torró
 
How angularjs saves rails
Michael He
 
RoR 101: Session 5
Rory Gianni
 
Laravel Eloquent ORM
Ba Thanh Huynh
 
Laravel overview
Obinna Akunne
 
Laravel introduction
Simon Funk
 
Rails Request & Middlewares
Santosh Wadghule
 

Similar to Intro to Ruby on Rails (20)

PDF
Apex Enterprise Patterns: Building Strong Foundations
Salesforce Developers
 
PDF
AGADOS function & feature Chapter-02 biz logic define
Yongkyoo Park
 
PDF
OSDC 2009 Rails Turtorial
Yi-Ting Cheng
 
KEY
Ruby For Startups
Mike Subelsky
 
PPT
Multi-tenancy with Rails
Paul Gallagher
 
ODP
DynamicRecord Presentation
linoj
 
PPT
Intro to Rails ActiveRecord
Mark Menard
 
KEY
Working Effectively With Legacy Code
scidept
 
PDF
2011-02-03 LA RubyConf Rails3 TDD Workshop
Wolfram Arnold
 
PDF
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Joao Lucas Santana
 
PDF
Rails antipattern-public
Chul Ju Hong
 
PDF
Rails antipatterns
Chul Ju Hong
 
PPT
Ruby On Rails
Gautam Rege
 
ODP
Pyramid deployment
Carlos de la Guardia
 
PDF
Phoenix for Rails Devs
Diacode
 
PPTX
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale
 
ODP
Practical catalyst
dwm042
 
PDF
Building Mobile Friendly APIs in Rails
Jim Jeffers
 
PDF
SproutCore and the Future of Web Apps
Mike Subelsky
 
PPT
Introduction To Code Igniter
Amzad Hossain
 
Apex Enterprise Patterns: Building Strong Foundations
Salesforce Developers
 
AGADOS function & feature Chapter-02 biz logic define
Yongkyoo Park
 
OSDC 2009 Rails Turtorial
Yi-Ting Cheng
 
Ruby For Startups
Mike Subelsky
 
Multi-tenancy with Rails
Paul Gallagher
 
DynamicRecord Presentation
linoj
 
Intro to Rails ActiveRecord
Mark Menard
 
Working Effectively With Legacy Code
scidept
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
Wolfram Arnold
 
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Joao Lucas Santana
 
Rails antipattern-public
Chul Ju Hong
 
Rails antipatterns
Chul Ju Hong
 
Ruby On Rails
Gautam Rege
 
Pyramid deployment
Carlos de la Guardia
 
Phoenix for Rails Devs
Diacode
 
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale
 
Practical catalyst
dwm042
 
Building Mobile Friendly APIs in Rails
Jim Jeffers
 
SproutCore and the Future of Web Apps
Mike Subelsky
 
Introduction To Code Igniter
Amzad Hossain
 
Ad

More from Mark Menard (14)

PDF
Let's Do Some Upfront Design - WindyCityRails 2014
Mark Menard
 
PDF
A Tour of Wyriki
Mark Menard
 
PDF
Small Code - RailsConf 2014
Mark Menard
 
PDF
Small Code - Ruby on Ales 2014
Mark Menard
 
PDF
Write Small Things (Code)
Mark Menard
 
PDF
JRuby 6 Years in Production
Mark Menard
 
PDF
Conference of Grand Masters Tech Talk 2013
Mark Menard
 
KEY
Startup Lessons Learned
Mark Menard
 
PDF
Mobile Platforms and App Development
Mark Menard
 
KEY
Ruby on Rails Training - Module 2
Mark Menard
 
KEY
Ruby on Rails Training - Module 1
Mark Menard
 
KEY
Introduction to Ruby
Mark Menard
 
PPT
Behavior Driven Development with Rails
Mark Menard
 
PPT
JRuby in a Java World
Mark Menard
 
Let's Do Some Upfront Design - WindyCityRails 2014
Mark Menard
 
A Tour of Wyriki
Mark Menard
 
Small Code - RailsConf 2014
Mark Menard
 
Small Code - Ruby on Ales 2014
Mark Menard
 
Write Small Things (Code)
Mark Menard
 
JRuby 6 Years in Production
Mark Menard
 
Conference of Grand Masters Tech Talk 2013
Mark Menard
 
Startup Lessons Learned
Mark Menard
 
Mobile Platforms and App Development
Mark Menard
 
Ruby on Rails Training - Module 2
Mark Menard
 
Ruby on Rails Training - Module 1
Mark Menard
 
Introduction to Ruby
Mark Menard
 
Behavior Driven Development with Rails
Mark Menard
 
JRuby in a Java World
Mark Menard
 
Ad

Recently uploaded (20)

PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 

Intro to Ruby on Rails

  • 1. Intro to Ruby on Rails by Mark Menard Vita Rara, Inc.
  • 2. Ruby © Vita Rara, Inc. “ I always knew one day Smalltalk would replace Java. I just didn’t know it would be called Ruby.” - Kent Beck, Creator of “Extreme Programming”
  • 3. Ruby on Rails Ruby on Rails is astounding. Using it is like watching a kung-fu movie, where a dozen bad-ass frameworks prepare to beat up the little newcomer only to be handed their asses in a variety of imaginative ways. -Nathan Torkington, O'Reilly Program Chair for OSCON © Vita Rara, Inc.
  • 4. The Elevator Pitch Ruby on Rails is an open-source web framework that is optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration. © Vita Rara, Inc.
  • 5. Overview Rails is a full stack web framework Model: ActiveRecord ORM database connectivity Database schema management View: ActiveView View layer Templates Controller: ActionController Web controller framework Manages web integration Active Support Extensions to Ruby to support web development Integrated Ajax support © Vita Rara, Inc.
  • 6. The Rails Philosophy Ruby - less and more readable code, shorter development times, simple but powerful, no compilation cycle. Convention over configuration Predefined directory structure, and naming conventions Best practices: MVC, DRY, Testing Almost everything in Rails is Ruby code (SQL and JavaScript are abstracted) Integrated AJAX support. Web services with REST. Good community, tools, and documentation Extracted from a real application: Basecamp © Vita Rara, Inc.
  • 7. Rake: The Ruby Make Rake lets you define a dependency tree of tasks to be executed. Rake tasks are loaded from the file Rakefile Rake automates and simplifies creating and managing the development of a Rails project. © Vita Rara, Inc.
  • 8. Environments Rails has support for multiple execution environments. Environments encapsulate database settings and other configuration. Typical environments Development Test Production Additional environments are easy to add. © Vita Rara, Inc.
  • 10. Managing Data Schemas Rails includes support for migrations to manage the evolution of your database schema. No need to write SQL. Migrations use a database independent Ruby API. Migrations are Ruby scripts giving you access to the full power of the language. © Vita Rara, Inc.
  • 11. Migrations Typical migration functions: create_table add_column change_column rename_column rename_table add_index © Vita Rara, Inc.
  • 12. Migration Example © Vita Rara, Inc. create_table &quot;users&quot; , :force => true do |t| t.string :login, :email, :remember_token t.string :salt, :crypted_password, :limit => 40 t.timestamps t.datetime :remember_token_expires_at end
  • 14. Fundamentals One database table maps to one Ruby class Table names are plural and class names are singular Database columns map to attributes, i.e. get and set methods, in the model class All tables have an integer primary key called id Database tables are created with migrations © Vita Rara, Inc.
  • 15. ActiveRecord Model Example © Vita Rara, Inc. create_table &quot;persons&quot; do |t| t.string :first_name, last_name t.timestamps end class Person < ActiveRecord::Base end p = Person.new p.first_name = ‘Mark’ p.last_name = ‘Menard’ p.save
  • 16. CRUD Create: create, new Read: find, find_by_<attribute> Update: save, update_attributes Delete: destroy © Vita Rara, Inc.
  • 17. Finding Models User.find(:first) User.find(:all) User.find(1) User.find_by_login(‘mark’) User.find(:all, :conditions => [ “login = ? AND password = ?”, login, password]) © Vita Rara, Inc.
  • 18. Advanced Finding Finders also support: :limit :offset :order :joins :select :group © Vita Rara, Inc.
  • 19. Update user = User.find(1) user.first_name = ‘Mark’ user.last_name = ‘Menard’ user.save! © Vita Rara, Inc.
  • 20. Transactions Account.transaction do account1.deposit(100) account2.withdraw(100) end © Vita Rara, Inc.
  • 22. ActiveRecord Associations Two primary types of associations: belongs_to has_one / has_many There are others, but they are not commonly used. © Vita Rara, Inc.
  • 23. ActiveRecord Associations © Vita Rara, Inc. # Has Many class Order < ActiveRecord::Base has_many :order_line_items end class OrderLineItem < ActiveRecord::Base belongs_to :order end # Has One class Party < ActiveRecord::Base has_one :login_credential end class LoginCredential < ActiveRecord::Base belongs_to :party end
  • 24. Association Methods Associations add methods to the class. This is an excellent example of meta-programming. Added methods allow easy management of the associated models. order.order_line_items << line_item order.order_line_items.create() © Vita Rara, Inc.
  • 26. Validation Validations are rules in your model objects to help protect the integrity of your data Validation is invoked by the save method. Save returns true if validations pass and false otherwise. If you invoke save! then a RecordInvalid exception is raised if the object is not valid Use save(false) if you need to turn off validation © Vita Rara, Inc.
  • 27. Validation Callback Methods validate validate_on_create validate_on_update © Vita Rara, Inc.
  • 28. Validation Example © Vita Rara, Inc. class Person < ActiveRecord::Base def validate puts “validate invoked” end def validate_on_create puts “validate_on_create invoked” end def validate_on_update puts “validate_on_update invoked” end end peter = Person.create(:name => “Peter”) # => validate, validate_on_create invoked peter.last_name = “Forsberg” peter.save # => validate_on_update invoked
  • 29. Validation Macros validates_acceptance_of validate_associated validates_confirmation_of validates_each validates_exclusion_of validates_format_of validates_inclusion_of validates_length_of validates_numericality_of validates_presence_of validates_size_of validates_uniqueness_of © Vita Rara, Inc.
  • 30. Validation Macro Example © Vita Rara, Inc. class User < ActiveRecord::Base validates_presence_of :name, :email, :password validates_format_of :name, :with => /^ \w +$/ , :message => “may only contain word characters” validates_uniqueness_of :name, :message => “is already in use” validates_length_of :password, :within => 4 .. 40 validates_confirmation_of :password validates_inclusion_of :role, :in => %w(super admin user) , :message => “must be super , admin, or user”, :allow_nil => true validates_presence_of :customer_id, :if => Proc. new { |u| %w(admin user) .include?(u.role) } validates_numericality_of :weight, :only_integer => true, :allow_nil => true end
  • 32. Controllers Controllers are Ruby classes that live under app/ controllers Controller classes extend ActionController::Base An action is a public method and/or a corresponding view template © Vita Rara, Inc.
  • 33. Rendering a Response A response is rendered with the render command An action can only render a response once Rails invokes render automatically if you don’t Redirects are made with the redirect_to command © Vita Rara, Inc.
  • 34. A Simple Controller © Vita Rara, Inc. class PrioritiesController < InternalController def show @priority = current_account.priorities.find(params[:id]) end def new @priority = Priority. new end def create @priority = Priority. new (params[:priority]) if @priority.save flash[:notice] = 'The priority was successfully created.' redirect_to account_url else render :action => &quot;new&quot; end end ... end
  • 35. Sessions A hash stored on the server, typically in a database table or in the file system. Keyed by the cookie _session_id Avoid storing complex Ruby objects, instead put id:s in the session and keep data in the database, i.e. use session[:user_id] rather than session[:user] © Vita Rara, Inc.
  • 36. ActionView Our Face to the World
  • 37. What is ActionView? ActionView is the module in the ActionPack library that deals with rendering a response to the client. The controller decides which template and/or partial and layout to use in the response Templates use helper methods to generate links, forms, and JavaScript, and to format text. © Vita Rara, Inc.
  • 38. Where do templates live? Templates that belong to a certain controller typically live under app/view/controller_name, i.e. templates for Admin::UsersController would live under app/ views/admin/users Templates shared across controllers are put under app/views/shared. You can render them with render :template => ‘shared/my_template’ You can have templates shared across Rails applications and render them with render :file => ‘path/to/template’ © Vita Rara, Inc.
  • 39. Template Environment Templates have access to the controller object’s flash, headers, logger, params, request, response, and session. Instance variables (i.e. @variable) in the controller are available in templates The current controller is available as the attribute controller. © Vita Rara, Inc.
  • 40. Embedded Ruby <%= ruby code here %> - Evaluates the Ruby code and prints the last evaluated value to the page. <% ruby code here %> - Evaluates Ruby code without outputting anything to the page. © Vita Rara, Inc.
  • 41. Example View © Vita Rara, Inc. <p> <b>Name:</b> <%=h @category.name %> </p> <%= link_to 'Edit' , edit_category_path(@category) %> | <%= link_to 'Back' , categories_path %>
  • 42. A Check Book Ledger Example
  • 43. Basic Requirements The System should allow the management of multiple accounts The system should maintain an account ledger for every account in the system. Each account ledger should consist of ledger entries. Each ledger entry can be either a positive or negative value. Ledger entries can be associated with a payee and a category. © Vita Rara, Inc.
  • 44. Implementing a Check Book Ledger Create a new project Theme the project Define our resources using: script/generate scaffold Account Ledger Entry Payee Category Theme models Implement © Vita Rara, Inc.
  • 46. Ruby and Rail Training One day to three day programs. Introduction to Ruby Advanced Ruby Introduction to Rails Advanced Rails Test Driven Development Behavior Driven Development Test Anything with Cucumber Advanced Domain Modeling with ActiveRecord Domain Driven Development with Rails © Vita Rara, Inc.
  • 47. Ruby on Rails Consulting Full Life Cycle Project Development Inception Implementation Deployment Long Term Support Ruby on Rails Mentoring Get your team up to speed using Rails © Vita Rara, Inc.
  • 48. Contact Information Mark Menard [email_address] http://www.vitarara.net / 518 369 7356 © Vita Rara, Inc.