SlideShare a Scribd company logo
[object Object]
Active Record
Part -2
Associations
Validations
Callbacks
Part -3
Testing Topics
Migrations
Migration allows you to define  changes  to your  database schema What is migration?
Why Migration? ,[object Object]
keep things  synchronized
The  model and scaffold  generators will  create migrations  appropriate for adding a new model. Auto generated migrations
ruby script/generate  model Product  name:string description:text  my_app/db/migrate/001_create_products.rb Creating a model
Migration generated class CreateProducts < ActiveRecord::Migration def  self.up   create_table  : products  do |t|  t.string :name  t.text :description  t.timestamps  end   end def  self.down   drop_table :products   end end
self.up / self.down
ruby script/generate migration  AddPartNumberToProducts   part_number:string my_app/db/migrate/002_AddPartNumberToProducts.rb  Creating a Standalone Migration
Migration generated class AddPartNumberToProducts < ActiveRecord::Migration   def  self.up   add_column :products, :part_number, :string  end  def  self.down   remove_column :products, :part_number  end end
rake   db:migrate also invokes the db:schema:dump task
schema_migrations  table
Other Transformations
def  self.up   create_table  :people do |t| t.string :username, :null => false t.string :fname,lname   t.text :notes   t.timestamps   end end def  self.down   drop_table :people end Creating a table
More transformations rename_column   :people ,  :fname ,  :first_name rename_table   old_name ,  new_name change_column   table_name ,  column_name , type remove_column  table_name ,  column_name add_index   table_name ,  column_name drop_table   table_name
More... change_table   :products  do |t|  t. remove  :description,  :name  t. string  :part_number  t. index  :part_number   t. rename  :upccode, :upc_code end
Rollback rake  db:rollback   rake db:rollback  STEP=3   rake db:migrate  VERSION=20080906120000
ActiveRecord
ActiveRecord is a Module ActiveRecord (note no space) could be classed as a module, since it's an implementation of the Active Record design pattern. (* need to ask)
One Class Per Table ,[object Object]
`id` int(11) NOT NULL    auto_increment,
`login` varchar(255),
`email` varchar(255),
`password` varchar(40),
`created_at` datetime default NULL,
`updated_at` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
One Object / instance   Per   Row
Table columns   map to   Object attributes
Some Key Points ,[object Object]
pluralized  table names.
integer  primary keys.
classname _id as  foreign keys .
Why Active Record ,[object Object]
hides  low level implementation
The Basics ,[object Object],[object Object]
end
person=Person.find(2)
find method Examples:  User. find (23)  User.find(:first)  User.find(:all, :offset => 10, :limit => 10)  User.find(:first).articles
Find :select list = Person.find(:all,  :select => &quot;fname, lname&quot; )
Find with :conditions Student.find(:all,  :conditions => [‘first_name = ? and status = ?’ ,‘mohit’, 1] ) Why this  ?
Find: Order By Person.find(:all,  :order => ‘updated_at DESC’ ) SQL: SELECT * FROM people ORDER BY created_at;
Find: Group By Person.find(:all,  :group => ‘designation’ ) SQL: SELECT * FROM people GROUP BY designation;
Find:  Limit & Offset Person.find(:all,  :limit => 10, :offset => 0 ) SQL: SELECT * FROM people LIMIT 0, 10
Dynamic find methods person  = Person.find_ by_fname (&quot;mohit&quot;) all_mohit = Person.find_ all_by_fname (&quot;mohit&quot;) person  = Person.find_ by_fname_and_lname (&quot;mohit&quot;,”jain”)
Creating a new record user = User.new user.name = &quot;David&quot; user.occupation = &quot;Code Artist“ user .save OR user =User. new (:name => &quot;David&quot;, :occupation  =>  &quot;Code Artist&quot;) user .save OR user =User .create (:name => &quot;David&quot;,    :occupation  =>  &quot;Code Artist&quot;)
Update a record person = Person.find(123)  person .update_attribute(:name, &quot;Barney&quot; ) OR person= Person.find(123) person .name = &quot;mohit” person.save OR person=Person. update(12, :name => &quot;jigar&quot; , :email => &quot;jigar@vinsol.com&quot; ) update_all and update_attribute bypass the validations.
Delete a record Person. delete (123)  OR person = Person.find_by_name(&quot;Mohit&quot;) person. destroy
Named and Anonymous Scopes
class  Organization  < ActiveRecord::Base  has_many :people named_scope :active, :conditions => { :active => 'Yes' } end class  Person  < ActiveRecord::Base  belongs_to :organization end Named scope
Usage Organization.active Organization.active.people
Named scope example 2 class  Order  < ActiveRecord::Base named_scope :last_n_days, lambda { |days| :condition => ['updated < ?' , days] } named_scope :checks, :conditions => {:pay_type => :check} end orders = Orders.last_n_days(7) orders = Orders.checks.last_n_days(7)
Anonymous scopes in_house = Orders.scoped(:conditions => 'email LIKE &quot;%@pragprog.com&quot;' ) in_house.checks.last_n_days(7)
Thank You.
Associations
[object Object]
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many Types of associations
Whats the  need ?
class  Customer  < ActiveRecord::Base  end  class  Order  < ActiveRecord::Base  end  OR class  Customer  < ActiveRecord::Base      has_many :orders, :dependent => :destroy   end  class  Order  < ActiveRecord::Base belongs_to :customer end  Comparison: without and with
The belongs_to Association
The has_one Association
One to One
The has_many Association
One to Many
Its: has_many : orders   and has_one : order
has_many :through
has_and_belongs_to_many
has_and_belongs_to_many  Stories can belong to many categories. Categories can have many stories. Categories_Stories Table story_id | category_id has_many through: -- gives you a  third model  Person can subscribe to many magazines. Magazines can have many subscribers. Subscriptions Table person_id | magazine_id | subscription_type |  subscription_length | subscription_date has_and_belongs_to_many  vs  has_many :through
Many  to  many
has_one :through
has_one:through* class  Magazine  < ActiveRecord::Base has_many :subscriptions end class  Subscription  < ActiveRecord::Base belongs_to :magazine belongs_to :user end class  User  < ActiveRecord::Base has_many :subscriptions has_one :magazine, :through => : subscriptions, :conditions => ['subscriptions.active = ?', true] end
Polymorphic Associations
Self refrentional Joins class  Employee  < ActiveRecord::Base has_many :subordinates ,  :class_name => &quot;Employee&quot; , : foreign_key =>    &quot;manager_id&quot; belongs_to :manager ,  :class_name => &quot;Employee&quot; end
When Things Get Saved class  Order  < ActiveRecord::Base has_one :invoice end class  Invoice  < ActiveRecord::Base belongs_to :order end continue...
When things get saved (continue) If you assign an object to a has_one/has_many association in an existing object, that associated object will be automatically saved. order = Order.find(some_id) an_invoice = Invoice.new(...) order.invoice = an_invoice  # invoice gets saved     continue...
When things get saved (continue) If instead you assign a new object to a belongs_to association, it will never be automatically saved. order = Order.new(...) an_invoice.order = orde r  # Order will not be saved here an_invoice.save   # both the invoice and the order get saved
Validations
validates_acceptance_of validates_confirmation_of validates_length_of validates_numericality_of validates_presence_of Validation Helpers
Example of validator helper class Person < ActiveRecord::Base  validates_presence_of   :name    validates_uniqueness_of  :name,   :on  => :create,   :message => &quot;is already used&quot;   end
When Does Validation Happen? new_record?  instance method
Method triggers validations * create * create! * save * save! * update * update_attributes * update_attributes!
Method skips validations * update_all * update_attribute * update_counters * save(false)
valid?  and  invalid?
Validation Errors errors.add_to_base errors.add errors.clear errors.size
Displaying Validation Errors error_messages error_messages_for
Showing error message OR <%=  error_messages_for  :product %>  <% form_for(@product) do |f| %>  <%= f. error_messages  %> #-----  <% end %>
Callbacks
monitoring the process.   The life cycle of a model object methods that get called at  certain moments  of an object’s lifecycle What are callbacks
Active Record defines  20 callbacks .
18 call backs
after_initialize  and  after_find Rest two callbacks

More Related Content

What's hot

Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
cfc
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
Clinton Dreisbach
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
Pavel Novitsky
 

What's hot (18)

Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Session 2 django material for training at baabtra models
Session 2 django material for training at baabtra modelsSession 2 django material for training at baabtra models
Session 2 django material for training at baabtra models
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design Examples
 
Christopher Latham Portfolio
Christopher Latham PortfolioChristopher Latham Portfolio
Christopher Latham Portfolio
 
2 years after the first event - The Saga Pattern
2 years after the first event - The Saga Pattern2 years after the first event - The Saga Pattern
2 years after the first event - The Saga Pattern
 
Functional GUIs with F#
Functional GUIs with F#Functional GUIs with F#
Functional GUIs with F#
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for Magento
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
java ee 6 Petcatalog
java ee 6 Petcatalogjava ee 6 Petcatalog
java ee 6 Petcatalog
 

Viewers also liked (8)

Ruby On Rails Presentation
Ruby On Rails PresentationRuby On Rails Presentation
Ruby On Rails Presentation
 
Ruby on rails. Best practices
Ruby on rails. Best practicesRuby on rails. Best practices
Ruby on rails. Best practices
 
Ruby association
Ruby associationRuby association
Ruby association
 
Ruby on Rails 中級者を目指して - 大場寧子
Ruby on Rails 中級者を目指して - 大場寧子Ruby on Rails 中級者を目指して - 大場寧子
Ruby on Rails 中級者を目指して - 大場寧子
 
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
 
表参道.rb #1 Ruby Gold 2.1 に合格した話
表参道.rb #1 Ruby Gold 2.1 に合格した話表参道.rb #1 Ruby Gold 2.1 に合格した話
表参道.rb #1 Ruby Gold 2.1 に合格した話
 
Feeding the sharks
Feeding the sharksFeeding the sharks
Feeding the sharks
 
Active Record PowerPoint
Active Record PowerPointActive Record PowerPoint
Active Record PowerPoint
 

Similar to Ruby on rails

OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
Yi-Ting Cheng
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
Kiev ALT.NET
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
AidIQ
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
fiyuer
 

Similar to Ruby on rails (20)

OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Intro to Rails ActiveRecord
Intro to Rails ActiveRecordIntro to Rails ActiveRecord
Intro to Rails ActiveRecord
 
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
 
Well
WellWell
Well
 
07 Php Mysql Update Delete
07 Php Mysql Update Delete07 Php Mysql Update Delete
07 Php Mysql Update Delete
 
Tech_Implementation of Complex ITIM Workflows
Tech_Implementation of Complex ITIM WorkflowsTech_Implementation of Complex ITIM Workflows
Tech_Implementation of Complex ITIM Workflows
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
WordPress plugin #2
WordPress plugin #2WordPress plugin #2
WordPress plugin #2
 
What's new in Rails 2?
What's new in Rails 2?What's new in Rails 2?
What's new in Rails 2?
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 
Lerman Vvs14 Ef Tips And Tricks
Lerman Vvs14  Ef Tips And TricksLerman Vvs14  Ef Tips And Tricks
Lerman Vvs14 Ef Tips And Tricks
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Simplify Your Rails Controllers With a Vengeance
Simplify Your Rails Controllers With a VengeanceSimplify Your Rails Controllers With a Vengeance
Simplify Your Rails Controllers With a Vengeance
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
 

Recently uploaded

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 

Recently uploaded (20)

Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

Ruby on rails