Active records
association
BY
ANANTA RAJ LAMICHHANE
Active record?
facilitates the creation and use of business objects whose data requires
persistent storage to a database.
is a description of an Object Relational Mapping system.
ORM, is a technique that connects the rich objects of an application to tables
in a relational database management system.
Convention over Configuration
Naming convention
Database Table - Plural with underscores separating words (e.g.,
book_clubs).
Model Class - Singular with the first letter of each word capitalized (e.g.,
BookClub).
Schema convention
Foreign keys - These fields should be named following the pattern
singularized_table_name_id.
Primary keys - By default, Active Record will use an integer column named
id as the table's primary key
optional column names like created_at, updated_at, type etcs….
AR associations. Why?
make common operations simpler and easier
Scenario
consider a simple Rails application that
includes a model for customers and a
model for orders.
Each customer can have many orders
rails g model customer name:string
rails g model order customer_id:integer
description:string
rake db:migrate
rails c
Without association
class Customer < ActiveRecord::Base
end
class Order < ActiveRecord::Base
end
2.1.1 :001 > c=Customer.create(name:'cust1')
=> #<Customer id: 1, name: "cust1", created_at: "2015-
01-03 07:58:03", updated_at: "2015-01-03 07:58:03">
To Add new Order
2.1.1 :002 > o=Order.new
2.1.1 :003 > o.customer_id=c.id
2.1.1 :003 > o.description="this is a test description"
2.1.1 :006 > o.save
To deleting a customer, and ensuring that all of its
orders get deleted as well
2.1.1 :009 > orders= Order.where(customer_id: c.id)
2.1.1 :010 > orders.each do |order|
2.1.1 :011 > order.destroy
2.1.1 :012?> end
2.1.1 :013 > c.destroy
With Association
class Customer < ActiveRecord::Base
has_many :orders, dependent: :destroy
end
class Order < ActiveRecord::Base
belongs_to :customer
end
2.1.1 :001 > c=Customer.create(name:'cust1')
=> #<Customer id: 1, name: "cust1", created_at: "2015-
01-03 07:58:03", updated_at: "2015-01-03 07:58:03">
To Add new Order
2.1.1 :002 > o=c.orders.create(description:”this is
first order”)
To deleting a customer, and ensuring that all of its
orders get deleted as well
2.1.1 :003 > c.destroy
Type of Association
belongs_to
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many
The belongs_to Association
a one-to-one connection, such that each
instance of the declaring model "belongs
to" one instance of the other model.
must use the singular term
Active record(1)
The has_one Association
has_one association also sets up a one-to-one connection with another
model
Active record(1)
class Customer < ActiveRecord::Base
has_one :order, dependent: :destroy
end
class Order < ActiveRecord::Base
belongs_to :customer
end
c.create_order(description:"ccc")
c.order
The has_many Association
a one-to-many connection.
the "other side" of a belongs_to association.
The name of the other model is pluralized
when declaring a has_many association.
Active record(1)
The has_many :through Association
a many-to-many connection
Active record(1)
rails g model physician name:string
rails g model patient name:string
rails g model appointment physician_id:integer patient_id:integer
description:string
rake db:migrate
rails c
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
2.1.1 :010 > p=Physician.find(1)
=> #<Physician id: 1, name: "physicain", created_at:
"2015-01-04 12:19:37", updated_at: "2015-01-04
12:19:37">
2.1.1 :012 > p.patients.create(name: "p2")
=> #<Patient id: 2, name: "p2", created_at: "2015-01-
04 12:43:22", updated_at: "2015-01-04 12:43:22">
2.1.1 :024 > p.appointments.where(patient_id:
2)[0].update_attributes(description:'test')
Alternatively,
p.appointments.create(patient_id: 2, description:
‘this is a test description’)
2.1.1 :030 > ph=Physician.find(1)
=> #<Physician id: 1, name: "physicain", created_at:
"2015-01-04 12:19:37", updated_at: "2015-01-04
12:19:37">
2.1.1 :031 > ph.patients << Patient.all
The has_one :through Association
a one-to-one connection with another model.
declaring model can be matched with one instance of
another model by proceeding through a third model.
if each supplier has one account, and each account is
associated with one account history, then the supplier
model could look like this:
Active record(1)
The has_and_belongs_to_many Association
creates a direct many-to-many connection
with another model, with no intervening
model.
Active record(1)
Classwork 1: Create two tables husband and wife with one on one relationship and test things.
Create a rails app which should have a database named 'blog_db' in MySQL. Then do the following
1. Create models Articles (title, content), Comments (comments, article_id), Tags (name)
2. Article should have many comments and each comment should be associated to one article
3. Each article can have many tags and each tag may be assigned to many articles.
4. Create the relation such that if we delete an article then all the comments associated with that
article is also deleted
5. Create a scope to query all the articles of yesterday sorted descending according to created date
Various options for
relations
class_name
dependent
polymorphic
validate
where
through
class_name: Controlling association scope
By default, associations look for objects only within the current module's scope. For example:
module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account
end
class Account < ActiveRecord::Base
belongs_to :supplier
end
end
end
Supplier and Account are defined in different scopes:
module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account
end
end
module Billing
class Account < ActiveRecord::Base
belongs_to :supplier
end
end
end
will not work!!
module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account,
class_name: "MyApplication::Billing::Account"
end
end
module Billing
class Account < ActiveRecord::Base
belongs_to :supplier,
class_name: "MyApplication::Business::Supplier"
end
end
end
or
if an order belongs to a customer, but the
actual name of the model containing
customers is Patron, you'd set things up
this way:
class Order < ActiveRecord::Base
belongs_to :customer, class_name: "Patron"
end
:validate
If you set the :validate option to true, then associated objects will be validated whenever you save this
object. By default, this is false: associated objects will not be validated when this object is saved.
class User
belongs_to :account
validates :account, :presence => true
end
.
class Order < ActiveRecord::Base
belongs_to :customer, -> { where active: true },
dependent: :destroy
end
Single table inheritance
allows inheritance by storing the name of the class in a
column that is named “type” by default.
a way to add inheritance to your models.
STI lets you save different models inheriting from the
same model inside a single table
Ref: http://samurails.com/tutorial/single-table-inheritance-
with-rails-4-part-1/
rails new sti --no-test-framework
rails g model animal name:string age:integer
race:string
rake db:migrate
# app/models/animal.rb
class Animal < ActiveRecord::Base
belongs_to :tribe
self.inheritance_column = :race
# We will need a way to know which animals
# will subclass the Animal model
def self.races
%w(Lion WildBoar Meerkat)
end
end
Note that self.inheritance_column = :race is used to
specify the column for STI and is not necessary if you
are using the default column type.
If you want to disable Single Table Inheritance or use
the type column for something else, you can use
self.inheritance_column = :fake_column.
# app/models/wild_boar.rb
class WildBoar < Animal
end
# app/models/meerkat.rb
class Meerkat < Animal
end
# app/models/lion.rb
class Lion < Animal
end
Lion.create(name:"himba", age:11)
Meerkat.create(name:"meerkat")
WildBoar.create(name:"wildboar")
2.1.1 :016 > Animal.all
=> # [#<Lion id: 1, name: "himba", age: "11",race: "Lion",
created_at: "2015-01-03 05:22:49", updated_at: "2015-
01-03 05:22:49">,
#<Animal id: 2, name: "ananta", age: nil, race: nil,
created_at: "2015-01-03 05:24:02", updated_at: "2015-
01-03 05:24:02">,
#<Meerkat id: 3, name: "wildboar", age: nil, race:
"Meerkat", created_at: "2015-01-03 05:25:03",
updated_at: "2015-01-03 05:25:03">,
#<WildBoar id: 4, name: "wildboar", age: nil, race:
"WildBoar", created_at: "2015-01-03 05:25:50",
updated_at: "2015-01-03 05:25:50">]>
Add scopes to the parent models for each child model
class Animal < ActiveRecord::Base
scope :lions, -> { where(race: 'Lion') }
scope :meerkats, -> { where(race: 'Meerkat') }
scope :wild_boars, -> { where(race: 'WildBoar') }
---
end
2.1.1 :001 > Animal.lions
Animal Load (0.2ms) SELECT "animals".*
FROM "animals" WHERE "animals"."race" =
'Lion'
=> #<ActiveRecord::Relation [#<Lion id: 1,
name: "himba", age: "11", race: "Lion",
created_at: "2015-01-03 05:22:49", updated_at:
"2015-01-03 05:22:49">]>
2.1.1 :002 > Animal.meerkats
Polymorphic association
ref: http://www.millwoodonline.co.uk/blog/polymorphic-associations-ruby-on-rails
Scenario:
Imagine a school or college system where both students
and teachers can add posts.
The post has an author->author could be a student or
a teacher.
The students and teachers can ->add many posts.
Therefore we need an association between the Student,
Teacher and Post models.
$ rails generate model student name:string email:string
$ rails generate model teacher name:string email:string office:integer
$ rails generate model post author:references{polymorphic}:index title:string
body:text
Note: created the post model with the author reference set as polymorphic and
an index
simplified by using the t.references form
author:references{polymorphic}:index
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.references :author, polymorphic:
true, index: true
t.string :title
t.text :body
t.timestamps
end
end
end
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :body
t.integer :author_id
t.string :author_type
t.timestamps
end
add_index :posts, :author_id
end
end
The Post model will already be setup correctly
# app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :author, polymorphic: true
end
# app/models/student.rb
class Student < ActiveRecord::Base
has_many :posts, as: :author
end
# app/models/teacher.rb
class Teacher < ActiveRecord::Base
has_many :posts, as: :author
end
2.1.1 :019 > s=Student.create(name: ‘Ananta’)
2.1.1 :019 > s=Student.find(1)
2.1.1 :011 > p=Post.new
=> #<Post id: nil, author_id: nil, author_type: nil, title:
nil, body: nil, created_at: nil, updated_at: nil>
2.1.1 :012 > p.author= s
=> #<Student id: 1, name: "ananta", email: nil,
created_at: "2015-01-03 07:06:51", updated_at: "2015-
01-03 07:06:51">
2.1.1 :013 > p.title="test title"
=> "test title"
2.1.1 :014 > p.save
2.1.1 :015 > Post.all
[#<Post id: 1, author_id: 1, author_type: "Student", title:
"test title", body: nil, created_at: "2015-01-03 07:08:02",
updated_at: "2015-01-03 07:08:02">
2.1.1 :019 > t=Teacher.create(name:"dddd")
=> #<Teacher id: 1, name: "dddd", email: nil, office: nil, created_at: "2015-01-03 07:15:02", updated_at: "2015-01-
03 07:15:02">
2.1.1 :020 > p=Post.create(author:t, title: "this is title", body:"this is body")
=> #<Post id: 2, author_id: 1, author_type: "Teacher", title: "this is title", body: "this is body", created_at: "2015-01-
03 07:16:31", updated_at: "2015-01-03 07:16:31">
2.1.1 :023 > Post.all
=> #<ActiveRecord::Relation
[#<Post id: 1, author_id: 1, author_type: "Student", title: "test title", body: nil, created_at: "2015-01-03 07:08:02",
updated_at: "2015-01-03 07:08:02">,
#<Post id: 2, author_id: 2, author_type: "Teacher", title: "this is title", body: "this is body", created_at: "2015-01-
03 07:16:31", updated_at: "2015-01-03 07:16:31">]>
2.1.1 :024 > p= Post.find(1)
=> #<Post id: 1, author_id: 1, author_type: "Student", title: "test title", body: nil, created_at: "2015-01-03 07:08:02",
updated_at: "2015-01-03 07:08:02">
2.1.1 :025 > p.author.name
=> "ananta"
POlymorphic many to any
association
Scopes
What is Scope?
A scope is a subset of a collection.
Scenario
You have Users.
Now, some of those Users are subscribed to your newsletter.
You marked those who receive a newsletter by adding a field to the Users
Database (user.subscribed_to_newsletter = true).
Naturally, you sometimes want to get those Users who are subscribed to
your newsletter.
ref: http://stackoverflow.com/questions/4869994/what-is-scope-named-scope-
in-rails
Active record(1)
of course, we always do this:
User.where(subscribed_to_newsletter: true)
Instead of always writing this you could, however, do something like this.
#File: users.rb
class User < ActiveRecord::Base
scope :newsletter, where(subscribed_to_newsletter: true)
end
This allows you to access your subscribers by simply doing this:
User.newsletter
Class methods on your model are automatically available on scopes. Assuming the following setup:
class Article < ActiveRecord::Base
scope :published, -> { where(published: true) }
scope :featured, -> { where(featured: true) }
def self.latest_article
order('published_at desc').first
end
def self.titles
pluck(:title)
end
end
We are able to call the methods like this:
Article.published.featured.latest_article
Article.featured.titles
default_scope
http://rails-bestpractices.com/posts/806-
default_scope-is-evil
class Post
default_scope where(published: true).order("created_at desc")
end
> Post.limit(10)
Post Load (3.3ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`published` = 1 ORDER BY
created_at desc LIMIT 10
> Post.unscoped.order("updated_at desc").limit(10)
Post Load (1.9ms) SELECT `posts`.* FROM `posts` ORDER BY updated_at desc LIMIT 10
Thank you

More Related Content

PDF
RubyOnRails-Cheatsheet-BlaineKendall
KEY
Building Web Service Clients with ActiveModel
PPTX
Create an other activity lesson 3
DOCX
My Portfolio
PPTX
Spring JDBCTemplate
DOCX
LearningMVCWithLINQToSQL
DOCX
How to convert custom plsql to web services-Soap OR Rest
PPTX
4. jsp
RubyOnRails-Cheatsheet-BlaineKendall
Building Web Service Clients with ActiveModel
Create an other activity lesson 3
My Portfolio
Spring JDBCTemplate
LearningMVCWithLINQToSQL
How to convert custom plsql to web services-Soap OR Rest
4. jsp

What's hot (18)

PPTX
Create an android app for database creation using.pptx
PDF
ASPNET_MVC_Tutorial_06_CS
PDF
Hibernate Mapping
KEY
Building Web Service Clients with ActiveModel
PDF
Backendless apps
PPS
Actionview
PDF
Android - Saving data
PPTX
VIPER Architecture
PDF
Design Summit - Navigating the ManageIQ Object Model - Brad Ascar
PDF
Vue.js 101
PDF
Data binding w Androidzie
PDF
Django workshop : let's make a blog
PDF
70562 (1)
ODT
Eclipse Tricks
PDF
Lab1-android
PDF
2 years after the first event - The Saga Pattern
PDF
Best Practices for Magento Debugging
PPTX
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Create an android app for database creation using.pptx
ASPNET_MVC_Tutorial_06_CS
Hibernate Mapping
Building Web Service Clients with ActiveModel
Backendless apps
Actionview
Android - Saving data
VIPER Architecture
Design Summit - Navigating the ManageIQ Object Model - Brad Ascar
Vue.js 101
Data binding w Androidzie
Django workshop : let's make a blog
70562 (1)
Eclipse Tricks
Lab1-android
2 years after the first event - The Saga Pattern
Best Practices for Magento Debugging
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Ad

Similar to Active record(1) (20)

PDF
Introduction to Active Record at MySQL Conference 2007
KEY
ActiveRecord Association (1), Season 2
PDF
Introduction to Active Record - Silicon Valley Ruby Conference 2007
PDF
Ruby association
PDF
Association in rails
ODP
Ruby on rails
PDF
ActiveRecord Query Interface (2), Season 2
PPTX
Querying with Rails
PPT
Intro to Rails ActiveRecord
PDF
Ruby on Rails ステップアップ講座 - 大場寧子
PPTX
associations.pptx
KEY
Active Record Query Interface (2), Season 1
KEY
ActiveRecord Associations (1), Season 1
KEY
ActiveRecord is Rotting Your Brian
PDF
Carlosbrando Rubyonrails21 En
PDF
Ruby on Rails 2.1 What's New
PPT
Active Record Data Modeling
KEY
ActiveRecord Associations (2), Season 1
PPTX
Moving ActiveRecord objects to the boundaries of your domain
PDF
Where's My SQL? Designing Databases with ActiveRecord Migrations
Introduction to Active Record at MySQL Conference 2007
ActiveRecord Association (1), Season 2
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Ruby association
Association in rails
Ruby on rails
ActiveRecord Query Interface (2), Season 2
Querying with Rails
Intro to Rails ActiveRecord
Ruby on Rails ステップアップ講座 - 大場寧子
associations.pptx
Active Record Query Interface (2), Season 1
ActiveRecord Associations (1), Season 1
ActiveRecord is Rotting Your Brian
Carlosbrando Rubyonrails21 En
Ruby on Rails 2.1 What's New
Active Record Data Modeling
ActiveRecord Associations (2), Season 1
Moving ActiveRecord objects to the boundaries of your domain
Where's My SQL? Designing Databases with ActiveRecord Migrations
Ad

Recently uploaded (20)

PDF
22EC502-MICROCONTROLLER AND INTERFACING-8051 MICROCONTROLLER.pdf
PDF
Soil Improvement Techniques Note - Rabbi
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PPTX
Amdahl’s law is explained in the above power point presentations
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PPTX
Feature types and data preprocessing steps
PDF
Improvement effect of pyrolyzed agro-food biochar on the properties of.pdf
PDF
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
PPTX
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
PPTX
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
PPTX
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
PDF
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
PDF
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PDF
ChapteR012372321DFGDSFGDFGDFSGDFGDFGDFGSDFGDFGFD
PPTX
communication and presentation skills 01
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
22EC502-MICROCONTROLLER AND INTERFACING-8051 MICROCONTROLLER.pdf
Soil Improvement Techniques Note - Rabbi
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Amdahl’s law is explained in the above power point presentations
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
Feature types and data preprocessing steps
Improvement effect of pyrolyzed agro-food biochar on the properties of.pdf
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
ChapteR012372321DFGDSFGDFGDFSGDFGDFGDFGSDFGDFGFD
communication and presentation skills 01
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF

Active record(1)

  • 2. Active record? facilitates the creation and use of business objects whose data requires persistent storage to a database. is a description of an Object Relational Mapping system. ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.
  • 3. Convention over Configuration Naming convention Database Table - Plural with underscores separating words (e.g., book_clubs). Model Class - Singular with the first letter of each word capitalized (e.g., BookClub). Schema convention Foreign keys - These fields should be named following the pattern singularized_table_name_id. Primary keys - By default, Active Record will use an integer column named id as the table's primary key optional column names like created_at, updated_at, type etcs….
  • 5. make common operations simpler and easier
  • 6. Scenario consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders
  • 7. rails g model customer name:string rails g model order customer_id:integer description:string rake db:migrate rails c
  • 8. Without association class Customer < ActiveRecord::Base end class Order < ActiveRecord::Base end
  • 9. 2.1.1 :001 > c=Customer.create(name:'cust1') => #<Customer id: 1, name: "cust1", created_at: "2015- 01-03 07:58:03", updated_at: "2015-01-03 07:58:03"> To Add new Order 2.1.1 :002 > o=Order.new 2.1.1 :003 > o.customer_id=c.id 2.1.1 :003 > o.description="this is a test description" 2.1.1 :006 > o.save To deleting a customer, and ensuring that all of its orders get deleted as well 2.1.1 :009 > orders= Order.where(customer_id: c.id) 2.1.1 :010 > orders.each do |order| 2.1.1 :011 > order.destroy 2.1.1 :012?> end 2.1.1 :013 > c.destroy
  • 10. With Association class Customer < ActiveRecord::Base has_many :orders, dependent: :destroy end class Order < ActiveRecord::Base belongs_to :customer end 2.1.1 :001 > c=Customer.create(name:'cust1') => #<Customer id: 1, name: "cust1", created_at: "2015- 01-03 07:58:03", updated_at: "2015-01-03 07:58:03"> To Add new Order 2.1.1 :002 > o=c.orders.create(description:”this is first order”) To deleting a customer, and ensuring that all of its orders get deleted as well 2.1.1 :003 > c.destroy
  • 13. The belongs_to Association a one-to-one connection, such that each instance of the declaring model "belongs to" one instance of the other model. must use the singular term
  • 15. The has_one Association has_one association also sets up a one-to-one connection with another model
  • 17. class Customer < ActiveRecord::Base has_one :order, dependent: :destroy end class Order < ActiveRecord::Base belongs_to :customer end c.create_order(description:"ccc") c.order
  • 18. The has_many Association a one-to-many connection. the "other side" of a belongs_to association. The name of the other model is pluralized when declaring a has_many association.
  • 20. The has_many :through Association a many-to-many connection
  • 22. rails g model physician name:string rails g model patient name:string rails g model appointment physician_id:integer patient_id:integer description:string rake db:migrate rails c
  • 23. class Physician < ActiveRecord::Base has_many :appointments has_many :patients, :through => :appointments end class Patient < ActiveRecord::Base has_many :appointments has_many :physicians, :through => :appointments end class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient end
  • 24. 2.1.1 :010 > p=Physician.find(1) => #<Physician id: 1, name: "physicain", created_at: "2015-01-04 12:19:37", updated_at: "2015-01-04 12:19:37"> 2.1.1 :012 > p.patients.create(name: "p2") => #<Patient id: 2, name: "p2", created_at: "2015-01- 04 12:43:22", updated_at: "2015-01-04 12:43:22"> 2.1.1 :024 > p.appointments.where(patient_id: 2)[0].update_attributes(description:'test') Alternatively, p.appointments.create(patient_id: 2, description: ‘this is a test description’) 2.1.1 :030 > ph=Physician.find(1) => #<Physician id: 1, name: "physicain", created_at: "2015-01-04 12:19:37", updated_at: "2015-01-04 12:19:37"> 2.1.1 :031 > ph.patients << Patient.all
  • 25. The has_one :through Association a one-to-one connection with another model. declaring model can be matched with one instance of another model by proceeding through a third model. if each supplier has one account, and each account is associated with one account history, then the supplier model could look like this:
  • 27. The has_and_belongs_to_many Association creates a direct many-to-many connection with another model, with no intervening model.
  • 29. Classwork 1: Create two tables husband and wife with one on one relationship and test things. Create a rails app which should have a database named 'blog_db' in MySQL. Then do the following 1. Create models Articles (title, content), Comments (comments, article_id), Tags (name) 2. Article should have many comments and each comment should be associated to one article 3. Each article can have many tags and each tag may be assigned to many articles. 4. Create the relation such that if we delete an article then all the comments associated with that article is also deleted 5. Create a scope to query all the articles of yesterday sorted descending according to created date
  • 32. class_name: Controlling association scope By default, associations look for objects only within the current module's scope. For example: module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account end class Account < ActiveRecord::Base belongs_to :supplier end end end
  • 33. Supplier and Account are defined in different scopes: module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account end end module Billing class Account < ActiveRecord::Base belongs_to :supplier end end end will not work!!
  • 34. module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account, class_name: "MyApplication::Billing::Account" end end module Billing class Account < ActiveRecord::Base belongs_to :supplier, class_name: "MyApplication::Business::Supplier" end end end
  • 35. or if an order belongs to a customer, but the actual name of the model containing customers is Patron, you'd set things up this way: class Order < ActiveRecord::Base belongs_to :customer, class_name: "Patron" end
  • 36. :validate If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved. class User belongs_to :account validates :account, :presence => true end .
  • 37. class Order < ActiveRecord::Base belongs_to :customer, -> { where active: true }, dependent: :destroy end
  • 39. allows inheritance by storing the name of the class in a column that is named “type” by default. a way to add inheritance to your models. STI lets you save different models inheriting from the same model inside a single table Ref: http://samurails.com/tutorial/single-table-inheritance- with-rails-4-part-1/
  • 40. rails new sti --no-test-framework rails g model animal name:string age:integer race:string rake db:migrate # app/models/animal.rb class Animal < ActiveRecord::Base belongs_to :tribe self.inheritance_column = :race # We will need a way to know which animals # will subclass the Animal model def self.races %w(Lion WildBoar Meerkat) end end Note that self.inheritance_column = :race is used to specify the column for STI and is not necessary if you are using the default column type. If you want to disable Single Table Inheritance or use the type column for something else, you can use self.inheritance_column = :fake_column.
  • 41. # app/models/wild_boar.rb class WildBoar < Animal end # app/models/meerkat.rb class Meerkat < Animal end # app/models/lion.rb class Lion < Animal end Lion.create(name:"himba", age:11) Meerkat.create(name:"meerkat") WildBoar.create(name:"wildboar") 2.1.1 :016 > Animal.all => # [#<Lion id: 1, name: "himba", age: "11",race: "Lion", created_at: "2015-01-03 05:22:49", updated_at: "2015- 01-03 05:22:49">, #<Animal id: 2, name: "ananta", age: nil, race: nil, created_at: "2015-01-03 05:24:02", updated_at: "2015- 01-03 05:24:02">, #<Meerkat id: 3, name: "wildboar", age: nil, race: "Meerkat", created_at: "2015-01-03 05:25:03", updated_at: "2015-01-03 05:25:03">, #<WildBoar id: 4, name: "wildboar", age: nil, race: "WildBoar", created_at: "2015-01-03 05:25:50", updated_at: "2015-01-03 05:25:50">]>
  • 42. Add scopes to the parent models for each child model class Animal < ActiveRecord::Base scope :lions, -> { where(race: 'Lion') } scope :meerkats, -> { where(race: 'Meerkat') } scope :wild_boars, -> { where(race: 'WildBoar') } --- end 2.1.1 :001 > Animal.lions Animal Load (0.2ms) SELECT "animals".* FROM "animals" WHERE "animals"."race" = 'Lion' => #<ActiveRecord::Relation [#<Lion id: 1, name: "himba", age: "11", race: "Lion", created_at: "2015-01-03 05:22:49", updated_at: "2015-01-03 05:22:49">]> 2.1.1 :002 > Animal.meerkats
  • 44. Scenario: Imagine a school or college system where both students and teachers can add posts. The post has an author->author could be a student or a teacher. The students and teachers can ->add many posts. Therefore we need an association between the Student, Teacher and Post models.
  • 45. $ rails generate model student name:string email:string $ rails generate model teacher name:string email:string office:integer $ rails generate model post author:references{polymorphic}:index title:string body:text Note: created the post model with the author reference set as polymorphic and an index
  • 46. simplified by using the t.references form author:references{polymorphic}:index class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.references :author, polymorphic: true, index: true t.string :title t.text :body t.timestamps end end end class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.string :title t.text :body t.integer :author_id t.string :author_type t.timestamps end add_index :posts, :author_id end end
  • 47. The Post model will already be setup correctly # app/models/post.rb class Post < ActiveRecord::Base belongs_to :author, polymorphic: true end # app/models/student.rb class Student < ActiveRecord::Base has_many :posts, as: :author end # app/models/teacher.rb class Teacher < ActiveRecord::Base has_many :posts, as: :author end 2.1.1 :019 > s=Student.create(name: ‘Ananta’) 2.1.1 :019 > s=Student.find(1) 2.1.1 :011 > p=Post.new => #<Post id: nil, author_id: nil, author_type: nil, title: nil, body: nil, created_at: nil, updated_at: nil> 2.1.1 :012 > p.author= s => #<Student id: 1, name: "ananta", email: nil, created_at: "2015-01-03 07:06:51", updated_at: "2015- 01-03 07:06:51"> 2.1.1 :013 > p.title="test title" => "test title" 2.1.1 :014 > p.save 2.1.1 :015 > Post.all [#<Post id: 1, author_id: 1, author_type: "Student", title: "test title", body: nil, created_at: "2015-01-03 07:08:02", updated_at: "2015-01-03 07:08:02">
  • 48. 2.1.1 :019 > t=Teacher.create(name:"dddd") => #<Teacher id: 1, name: "dddd", email: nil, office: nil, created_at: "2015-01-03 07:15:02", updated_at: "2015-01- 03 07:15:02"> 2.1.1 :020 > p=Post.create(author:t, title: "this is title", body:"this is body") => #<Post id: 2, author_id: 1, author_type: "Teacher", title: "this is title", body: "this is body", created_at: "2015-01- 03 07:16:31", updated_at: "2015-01-03 07:16:31"> 2.1.1 :023 > Post.all => #<ActiveRecord::Relation [#<Post id: 1, author_id: 1, author_type: "Student", title: "test title", body: nil, created_at: "2015-01-03 07:08:02", updated_at: "2015-01-03 07:08:02">, #<Post id: 2, author_id: 2, author_type: "Teacher", title: "this is title", body: "this is body", created_at: "2015-01- 03 07:16:31", updated_at: "2015-01-03 07:16:31">]> 2.1.1 :024 > p= Post.find(1) => #<Post id: 1, author_id: 1, author_type: "Student", title: "test title", body: nil, created_at: "2015-01-03 07:08:02", updated_at: "2015-01-03 07:08:02"> 2.1.1 :025 > p.author.name => "ananta"
  • 49. POlymorphic many to any association
  • 51. What is Scope? A scope is a subset of a collection.
  • 52. Scenario You have Users. Now, some of those Users are subscribed to your newsletter. You marked those who receive a newsletter by adding a field to the Users Database (user.subscribed_to_newsletter = true). Naturally, you sometimes want to get those Users who are subscribed to your newsletter. ref: http://stackoverflow.com/questions/4869994/what-is-scope-named-scope- in-rails
  • 54. of course, we always do this: User.where(subscribed_to_newsletter: true) Instead of always writing this you could, however, do something like this. #File: users.rb class User < ActiveRecord::Base scope :newsletter, where(subscribed_to_newsletter: true) end This allows you to access your subscribers by simply doing this: User.newsletter
  • 55. Class methods on your model are automatically available on scopes. Assuming the following setup: class Article < ActiveRecord::Base scope :published, -> { where(published: true) } scope :featured, -> { where(featured: true) } def self.latest_article order('published_at desc').first end def self.titles pluck(:title) end end We are able to call the methods like this: Article.published.featured.latest_article Article.featured.titles
  • 57. class Post default_scope where(published: true).order("created_at desc") end > Post.limit(10) Post Load (3.3ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`published` = 1 ORDER BY created_at desc LIMIT 10 > Post.unscoped.order("updated_at desc").limit(10) Post Load (1.9ms) SELECT `posts`.* FROM `posts` ORDER BY updated_at desc LIMIT 10