SlideShare a Scribd company logo
1 of 19
Download to read offline
Rails Tips and Best Practices
   By David Keener

            http://www.keenertech.com

                                        Version 1.1 - April 28, 2012
Introduction

Ruby on Rails is an exciting technology…a well-
crafted framework with innovative philosophies
baked in to facilitate Agile Web Development

            • But even so, there are pitfalls…

            •     A few simple tips can help you avoid
            •     the most common pitfalls
The Log File is Your Friend

You can’t optimize if you don’t know what your
code is doing -- leverage the log file….

                   • Beginning Rails developers write
                     inefficient code
                     - Log File: /log/development.log
                   • Shows all web page parameters
                     - Posted Fields
                     - URL Parameters
                   • Shows all executed SQL
A Sample Log File
Processing LoginController#index (for 127.0.0.1 at 2009-08-27 03:33:44) [POST]
Parameters: {"x"=>"25", "y"=>"10”, "authenticity_token"=>"bVOEM1qk1F4AH0=",
    "login_name"=>"dkeener@keenertech.com", "password"=>”sample"}
[4;36;1mUser Columns (2.5ms)[0m [0;1mSHOW FIELDS FROM `users`[0m
 [4;35;1mUser Load (40.8ms)[0m [0mSELECT * FROM `users` WHERE
    (`users`.`password` = ’gHyfrds76jD' AND `users`.`email` =
    'dkeener@keenertech.com') LIMIT 1[0m
[4;36;1mProfile Columns (2.1ms)[0m [0;1mSHOW FIELDS FROM `profiles`[0m
[4;35;1mProfile Load (1.2ms)[0m [0mSELECT * FROM `profiles` WHERE
    (`profiles`.`user_id` = 3) LIMIT 1[0m
[4;36;1mUser Update (0.3ms)[0m [0;1mUPDATE `users` SET `login_count` = 4,
    `updated_at` = '2009-08-27 07:33:45' WHERE `id` = 3[0m
Redirected to http://127.0.0.1:3000/
Completed in 624ms (DB: 48) | 302 Found [http://127.0.0.1/login]
My Program Blew Up on a Query
“I was doing a find(45) and my code blew up!”

      • find(#) raises a RecordNotFound exception if
        it doesn’t find a matching row

      • But find_by_id(#) returns nil if not found

      • And the first, all and last methods return
        nil if they fail

      It’s easy to forget about this…
Column Definitions
Rails makes building your database easy…
rails generate model User first_name:string
   last_name:string login_name:string
   password:string

      • Defaults to NULL-able columns
        - If it’s required, it should be NOT NULL
      • Strings => varchar(255)
        - Why worry about storage? Just use the default size
        - Let model validations handle size constraints (if any)
A Typical Migration (Excerpt)
def self.up
 create_table :users do |t|
    t.string :first_name, :null => false
    t.string :last_name, :null => false
    t.string :login_name, :null => false
    t.string :email, :null => false
    t.string :password
    t.integer :login_count, :null => false, :default => 0
    t.boolean :is_active, :null => false, :default => true
    t.timestamps
 end
end
Foreign Key Constraints
Do you use foreign key constraints or not?

      • Rails discourages foreign keys
      • Rails promotes enforcement of data integrity
        via the model (with validations)
      • Rails defines model relationships (with
        associations)


      Do you need foreign keys?
                My answer: It depends….
Think of your database
           as a source of water.




                       If your app is a…
…Walled Fortress, with a well in the central
 courtyard that can only be accessed
 through controlled means – then
  you don’t need foreign keys
…Wildlife Preserve, with a pond that
 serves as a watering hole for all sorts of
 animals – then you need foreign keys
Foreign Key Helper Code
module MigrationHelpers
 def fk(from_table, from_column, to_table)
  execute “alter table #{from_table}
          add constraint #{constraint(from_table, from_column)}
          foreign key (#{from_column}) references #{to_table}(id)”
 end

 def drop_fk(from_table, from_column)
  execute “alter table #{from_table}
        drop foreign key #{constraint(from_table, from_column)}”
 end

 def constraint(table, column)
  "fk_#{table}_#{column}"
 end
end
Conditional Logic in Migrations
Migrations are Ruby. You can do anything in Ruby...

   •   Find out what database is in use:
       Rails 2.3.x
       adapter = User.connection.instance_variable_get("@config")[:adapter]
       Rails 3.x
       adapter = connection.adapter_name.downcase.to_sym

   •   Find out what environment is in use:
       if RAILS_ENV == ‘production’ …       # Rails 2.3.x
       if Rails.env == :production …        # Rails 3.x

   Especially useful if environments are different, e.g. – your laptop
   dev environment uses MySQL, but production uses Oracle
Fixture Recommendations
Fixtures are nice, but problematic.


       • Can use fixtures for “lookup” data – e.g.
         states, countries, etc.
       • Reference in both migrations and tests
       • Also consider seeds for data
       • For dynamic test data, use tools like
         FactoryGirl or Machinist
Loading a Fixture in a Migration
require 'active_record/fixtures’

class CreateCountries < ActiveRecord::Migration
  def self.up
   create_table :countries do |t|
   end

  Fixtures.create_fixtures('test/fixtures', File.basename("countries.yml", '.*'))
 end

 def self.down
   drop_table :countries
 end
end
Delegation
• Old-style convenience method to pull data
  from other models
   # In the User model…             Does user have a profile?
   def birthday                     Is caller aware of DB call?
      self.profile.birthday
   end


• New-style using delegation

   # In the User model…
   delegate :birthday, :to => :profile
Limit what you bring back with find
 - Use the will_paginate gem
 - Or use limits: User.limit(5)         # Rails 3.x
                  User.all(:limit => 5) # Rails 2.3.
Don’t create methods with
the same name as associations –
BAD IDEA
Conclusion
• Harness the power of Rails
  - But understand what it’s doing for you
• Minimize database calls, but don’t go crazy
  - Try eager loading in your find statements
• The console is your friend…use it…
• Consider data integrity in your apps
  - Or somebody will pay the price later
• Test, test, test
  - Try RSpec, Factory Girl and SimpleCov, etc.

More Related Content

What's hot

Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scopingPatrick Sheridan
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2Maksym Tolstik
 
You Used To Inject Me In Your Constructor
 You Used To Inject Me In Your Constructor You Used To Inject Me In Your Constructor
You Used To Inject Me In Your ConstructorVeronica Lillie
 
Effect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmapEffect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmapJoost de Vries
 
Introduction to React by Ebowe Blessing
Introduction to React by Ebowe BlessingIntroduction to React by Ebowe Blessing
Introduction to React by Ebowe BlessingBlessing Ebowe
 

What's hot (9)

Akka framework
Akka frameworkAkka framework
Akka framework
 
Akka - A Brief Intro
Akka - A Brief IntroAkka - A Brief Intro
Akka - A Brief Intro
 
Part 2 Python
Part 2 PythonPart 2 Python
Part 2 Python
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2
 
You Used To Inject Me In Your Constructor
 You Used To Inject Me In Your Constructor You Used To Inject Me In Your Constructor
You Used To Inject Me In Your Constructor
 
Effect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmapEffect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmap
 
Introduction to React by Ebowe Blessing
Introduction to React by Ebowe BlessingIntroduction to React by Ebowe Blessing
Introduction to React by Ebowe Blessing
 
Introduction to the Actor Model
Introduction to the Actor ModelIntroduction to the Actor Model
Introduction to the Actor Model
 

Viewers also liked

Louise d - trial presentation
Louise d - trial presentationLouise d - trial presentation
Louise d - trial presentationTrailplan
 
Early release october 2014 engagement & curriculum
Early release october 2014 engagement & curriculumEarly release october 2014 engagement & curriculum
Early release october 2014 engagement & curriculumJennifer Marten
 
MedicinMan June 2012 Issue
MedicinMan June  2012 IssueMedicinMan June  2012 Issue
MedicinMan June 2012 IssueAnup Soans
 
MedicinMan December 2011
MedicinMan December 2011MedicinMan December 2011
MedicinMan December 2011Anup Soans
 
Pesquisa Ibope Alvorada FM Março de 2012
Pesquisa Ibope Alvorada FM Março de 2012Pesquisa Ibope Alvorada FM Março de 2012
Pesquisa Ibope Alvorada FM Março de 2012fabricandoweb
 
Content area read alouds
Content area read aloudsContent area read alouds
Content area read aloudsS Bryce Kozla
 
Penerjemahan Teks Teknologi Informasi
Penerjemahan Teks Teknologi InformasiPenerjemahan Teks Teknologi Informasi
Penerjemahan Teks Teknologi InformasiBahtera
 
Dafo came safa urgel pii
Dafo   came safa urgel piiDafo   came safa urgel pii
Dafo came safa urgel piiFernando Guadix
 
Accelerate Journey To The Cloud
Accelerate Journey To The CloudAccelerate Journey To The Cloud
Accelerate Journey To The CloudMark Treweeke
 
Supplier or Partner
Supplier or PartnerSupplier or Partner
Supplier or Partnerjimholc385
 
Individual sections development exercise #5
Individual sections development exercise #5Individual sections development exercise #5
Individual sections development exercise #5tykl94
 

Viewers also liked (20)

RPforEUH2031
RPforEUH2031RPforEUH2031
RPforEUH2031
 
Louise d - trial presentation
Louise d - trial presentationLouise d - trial presentation
Louise d - trial presentation
 
Best of The Talking Village Blog
Best of The Talking Village BlogBest of The Talking Village Blog
Best of The Talking Village Blog
 
Early release october 2014 engagement & curriculum
Early release october 2014 engagement & curriculumEarly release october 2014 engagement & curriculum
Early release october 2014 engagement & curriculum
 
Hot Air Hand Tools
Hot Air Hand ToolsHot Air Hand Tools
Hot Air Hand Tools
 
MedicinMan June 2012 Issue
MedicinMan June  2012 IssueMedicinMan June  2012 Issue
MedicinMan June 2012 Issue
 
Vendere con motori di ricerca e social network. Olos27102011
Vendere con motori di ricerca e social network. Olos27102011Vendere con motori di ricerca e social network. Olos27102011
Vendere con motori di ricerca e social network. Olos27102011
 
MedicinMan December 2011
MedicinMan December 2011MedicinMan December 2011
MedicinMan December 2011
 
Pesquisa Ibope Alvorada FM Março de 2012
Pesquisa Ibope Alvorada FM Março de 2012Pesquisa Ibope Alvorada FM Março de 2012
Pesquisa Ibope Alvorada FM Março de 2012
 
Content area read alouds
Content area read aloudsContent area read alouds
Content area read alouds
 
Penerjemahan Teks Teknologi Informasi
Penerjemahan Teks Teknologi InformasiPenerjemahan Teks Teknologi Informasi
Penerjemahan Teks Teknologi Informasi
 
One 2 One Rollover
One 2 One RolloverOne 2 One Rollover
One 2 One Rollover
 
Dafo came safa urgel pii
Dafo   came safa urgel piiDafo   came safa urgel pii
Dafo came safa urgel pii
 
Tobacco Cessation: Accept The Challenge
Tobacco Cessation: Accept The ChallengeTobacco Cessation: Accept The Challenge
Tobacco Cessation: Accept The Challenge
 
CQ Associates v8
CQ Associates v8CQ Associates v8
CQ Associates v8
 
Magico
MagicoMagico
Magico
 
P kzach
P kzachP kzach
P kzach
 
Accelerate Journey To The Cloud
Accelerate Journey To The CloudAccelerate Journey To The Cloud
Accelerate Journey To The Cloud
 
Supplier or Partner
Supplier or PartnerSupplier or Partner
Supplier or Partner
 
Individual sections development exercise #5
Individual sections development exercise #5Individual sections development exercise #5
Individual sections development exercise #5
 

Similar to Rails Tips and Best Practices

Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementLaurent Leturgez
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...InfluxData
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersJonathan Levin
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesMats Kindahl
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World DominationcPanel
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseSpeedment, Inc.
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSpeedment, Inc.
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersMichael Rys
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on RailsAvi Kedar
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscriptBill Buchan
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Jan Helke
 
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Yasuko Ohba
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performanceEngine Yard
 
Building an ML Platform with Ray and MLflow
Building an ML Platform with Ray and MLflowBuilding an ML Platform with Ray and MLflow
Building an ML Platform with Ray and MLflowDatabricks
 

Similar to Rails Tips and Best Practices (20)

Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL Databases
 
Rails israel 2013
Rails israel 2013Rails israel 2013
Rails israel 2013
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World Domination
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Rails Security
Rails SecurityRails Security
Rails Security
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your database
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your database
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for Developers
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']
 
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 
Building an ML Platform with Ray and MLflow
Building an ML Platform with Ray and MLflowBuilding an ML Platform with Ray and MLflow
Building an ML Platform with Ray and MLflow
 

More from David Keener

Writing Killer Fight Scenes
Writing Killer Fight ScenesWriting Killer Fight Scenes
Writing Killer Fight ScenesDavid Keener
 
Build a Space Battle
Build a Space BattleBuild a Space Battle
Build a Space BattleDavid Keener
 
Creating an Adaptive Setting
Creating an Adaptive SettingCreating an Adaptive Setting
Creating an Adaptive SettingDavid Keener
 
Public Speaking for Writers
Public Speaking for WritersPublic Speaking for Writers
Public Speaking for WritersDavid Keener
 
21st Century Writer
21st Century Writer21st Century Writer
21st Century WriterDavid Keener
 
Titanic: The Forgotten Passengers
Titanic: The Forgotten PassengersTitanic: The Forgotten Passengers
Titanic: The Forgotten PassengersDavid Keener
 
Elevator Up, Please!
Elevator Up, Please!Elevator Up, Please!
Elevator Up, Please!David Keener
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineDavid Keener
 
Killer Business Models
Killer Business ModelsKiller Business Models
Killer Business ModelsDavid Keener
 
Building Facebook Apps
Building Facebook AppsBuilding Facebook Apps
Building Facebook AppsDavid Keener
 
Leveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsLeveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsDavid Keener
 
Quick Start: ActiveScaffold
Quick Start: ActiveScaffoldQuick Start: ActiveScaffold
Quick Start: ActiveScaffoldDavid Keener
 
Creating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsCreating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsDavid Keener
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On RailsDavid Keener
 
Using Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyUsing Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyDavid Keener
 
Implementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteImplementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteDavid Keener
 
Creating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartCreating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartDavid Keener
 
Quick Start: Rails
Quick Start: RailsQuick Start: Rails
Quick Start: RailsDavid Keener
 

More from David Keener (20)

Writing Killer Fight Scenes
Writing Killer Fight ScenesWriting Killer Fight Scenes
Writing Killer Fight Scenes
 
Build a Space Battle
Build a Space BattleBuild a Space Battle
Build a Space Battle
 
Creating an Adaptive Setting
Creating an Adaptive SettingCreating an Adaptive Setting
Creating an Adaptive Setting
 
Public Speaking for Writers
Public Speaking for WritersPublic Speaking for Writers
Public Speaking for Writers
 
21st Century Writer
21st Century Writer21st Century Writer
21st Century Writer
 
Titanic: The Forgotten Passengers
Titanic: The Forgotten PassengersTitanic: The Forgotten Passengers
Titanic: The Forgotten Passengers
 
Elevator Up, Please!
Elevator Up, Please!Elevator Up, Please!
Elevator Up, Please!
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search Engine
 
Killer Business Models
Killer Business ModelsKiller Business Models
Killer Business Models
 
Rails Security
Rails SecurityRails Security
Rails Security
 
Building Facebook Apps
Building Facebook AppsBuilding Facebook Apps
Building Facebook Apps
 
Leveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsLeveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook Apps
 
Quick Start: ActiveScaffold
Quick Start: ActiveScaffoldQuick Start: ActiveScaffold
Quick Start: ActiveScaffold
 
Creating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsCreating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector Graphics
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On Rails
 
Using Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyUsing Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case Study
 
Practical JRuby
Practical JRubyPractical JRuby
Practical JRuby
 
Implementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteImplementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking Site
 
Creating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartCreating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChart
 
Quick Start: Rails
Quick Start: RailsQuick Start: Rails
Quick Start: Rails
 

Recently uploaded

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Recently uploaded (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Rails Tips and Best Practices

  • 1. Rails Tips and Best Practices By David Keener http://www.keenertech.com Version 1.1 - April 28, 2012
  • 2. Introduction Ruby on Rails is an exciting technology…a well- crafted framework with innovative philosophies baked in to facilitate Agile Web Development • But even so, there are pitfalls… • A few simple tips can help you avoid • the most common pitfalls
  • 3. The Log File is Your Friend You can’t optimize if you don’t know what your code is doing -- leverage the log file…. • Beginning Rails developers write inefficient code - Log File: /log/development.log • Shows all web page parameters - Posted Fields - URL Parameters • Shows all executed SQL
  • 4. A Sample Log File Processing LoginController#index (for 127.0.0.1 at 2009-08-27 03:33:44) [POST] Parameters: {"x"=>"25", "y"=>"10”, "authenticity_token"=>"bVOEM1qk1F4AH0=", "login_name"=>"dkeener@keenertech.com", "password"=>”sample"} [4;36;1mUser Columns (2.5ms)[0m [0;1mSHOW FIELDS FROM `users`[0m [4;35;1mUser Load (40.8ms)[0m [0mSELECT * FROM `users` WHERE (`users`.`password` = ’gHyfrds76jD' AND `users`.`email` = 'dkeener@keenertech.com') LIMIT 1[0m [4;36;1mProfile Columns (2.1ms)[0m [0;1mSHOW FIELDS FROM `profiles`[0m [4;35;1mProfile Load (1.2ms)[0m [0mSELECT * FROM `profiles` WHERE (`profiles`.`user_id` = 3) LIMIT 1[0m [4;36;1mUser Update (0.3ms)[0m [0;1mUPDATE `users` SET `login_count` = 4, `updated_at` = '2009-08-27 07:33:45' WHERE `id` = 3[0m Redirected to http://127.0.0.1:3000/ Completed in 624ms (DB: 48) | 302 Found [http://127.0.0.1/login]
  • 5. My Program Blew Up on a Query “I was doing a find(45) and my code blew up!” • find(#) raises a RecordNotFound exception if it doesn’t find a matching row • But find_by_id(#) returns nil if not found • And the first, all and last methods return nil if they fail It’s easy to forget about this…
  • 6. Column Definitions Rails makes building your database easy… rails generate model User first_name:string last_name:string login_name:string password:string • Defaults to NULL-able columns - If it’s required, it should be NOT NULL • Strings => varchar(255) - Why worry about storage? Just use the default size - Let model validations handle size constraints (if any)
  • 7. A Typical Migration (Excerpt) def self.up create_table :users do |t| t.string :first_name, :null => false t.string :last_name, :null => false t.string :login_name, :null => false t.string :email, :null => false t.string :password t.integer :login_count, :null => false, :default => 0 t.boolean :is_active, :null => false, :default => true t.timestamps end end
  • 8. Foreign Key Constraints Do you use foreign key constraints or not? • Rails discourages foreign keys • Rails promotes enforcement of data integrity via the model (with validations) • Rails defines model relationships (with associations) Do you need foreign keys? My answer: It depends….
  • 9. Think of your database as a source of water. If your app is a…
  • 10. …Walled Fortress, with a well in the central courtyard that can only be accessed through controlled means – then you don’t need foreign keys
  • 11. …Wildlife Preserve, with a pond that serves as a watering hole for all sorts of animals – then you need foreign keys
  • 12. Foreign Key Helper Code module MigrationHelpers def fk(from_table, from_column, to_table) execute “alter table #{from_table} add constraint #{constraint(from_table, from_column)} foreign key (#{from_column}) references #{to_table}(id)” end def drop_fk(from_table, from_column) execute “alter table #{from_table} drop foreign key #{constraint(from_table, from_column)}” end def constraint(table, column) "fk_#{table}_#{column}" end end
  • 13. Conditional Logic in Migrations Migrations are Ruby. You can do anything in Ruby... • Find out what database is in use: Rails 2.3.x adapter = User.connection.instance_variable_get("@config")[:adapter] Rails 3.x adapter = connection.adapter_name.downcase.to_sym • Find out what environment is in use: if RAILS_ENV == ‘production’ … # Rails 2.3.x if Rails.env == :production … # Rails 3.x Especially useful if environments are different, e.g. – your laptop dev environment uses MySQL, but production uses Oracle
  • 14. Fixture Recommendations Fixtures are nice, but problematic. • Can use fixtures for “lookup” data – e.g. states, countries, etc. • Reference in both migrations and tests • Also consider seeds for data • For dynamic test data, use tools like FactoryGirl or Machinist
  • 15. Loading a Fixture in a Migration require 'active_record/fixtures’ class CreateCountries < ActiveRecord::Migration def self.up create_table :countries do |t| end Fixtures.create_fixtures('test/fixtures', File.basename("countries.yml", '.*')) end def self.down drop_table :countries end end
  • 16. Delegation • Old-style convenience method to pull data from other models # In the User model… Does user have a profile? def birthday Is caller aware of DB call? self.profile.birthday end • New-style using delegation # In the User model… delegate :birthday, :to => :profile
  • 17. Limit what you bring back with find - Use the will_paginate gem - Or use limits: User.limit(5) # Rails 3.x User.all(:limit => 5) # Rails 2.3.
  • 18. Don’t create methods with the same name as associations – BAD IDEA
  • 19. Conclusion • Harness the power of Rails - But understand what it’s doing for you • Minimize database calls, but don’t go crazy - Try eager loading in your find statements • The console is your friend…use it… • Consider data integrity in your apps - Or somebody will pay the price later • Test, test, test - Try RSpec, Factory Girl and SimpleCov, etc.