SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
http://jy
aasa.comCopyright 2016. Jyaasa Technologies.
Association in
rails
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Associate Software Engineer at
Jyaasa Technologies
Hello !
I am Sarbada Nanda Jaiswal
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
What is the
association?
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
In Rails, an association is a connection between two
Active Record models.
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Why associations?
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Because they make common operations simpler and
easier in your code.
For example: Includes a model for authors and a
model for books. Each author can have many books.
The model declarations would look like:
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Without associations With Active Record associations
class Author < ApplicationRecord
end
class Book < ApplicationRecord
end
class Author < ApplicationRecord
has_many :books, dependent: :destroy
end
class Book < ApplicationRecord
belongs_to :author
end
@book = Book.create(published_at: Time.now,
author_id: @author.id)
@book = @author.books.create(published_at:
Time.now)
@books = Book.where(author_id: @author.id)
@books.each do |book|
book.destroy
end
@author.destroy
@author.destroy
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The Types of Associations
Rails supports six types of associations:
● belongs_to
● has_one
● has_many
● has_many :through
● has_one :through
● has_and_belongs_to_many
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The belongs_to Association
A one-to-one connection with another model.
Each instance of the declaring model "belongs to" one instance of
the other model.
For example, if your application includes authors and books, and
each book can be assigned to exactly one author then how would
be declared the book model?
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
class CreateBooks < ActiveRecord::Migration[5.0]
def change
create_table :authors do |t|
t.string :name
t.timestamps
end
create_table :books do |t|
t.belongs_to :author, index: true
t.datetime :published_at
t.timestamps
end
end
end
The corresponding migration might look like this:
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The has_one Association
A one-to-one connection with another model.
Each instance of a model contains or possesses one
instance of another model.
For example, if each supplier in your application has only one
account. How would be declared the supplier model?
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
class CreateSuppliers <
ActiveRecord::Migration[5.0]
def change
create_table :suppliers do |t|
t.string :name
t.timestamps
end
create_table :accounts do |t|
t.belongs_to :supplier, index: true
t.string :account_number
t.timestamps
end
end
end
The corresponding migration might look like this:
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Depending on the use case, you might also need to create a unique index
and/or a foreign key constraint on the supplier column for the accounts table.
In this case, the column definition might look like this:
create_table :accounts do |t|
t.belongs_to :supplier, index: true, unique: true, foreign_key: true
# ...
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The has_many Association
A one-to-many connection with another model.
This association on the "other side" of a belongs_to association.
Each instance of the model has zero or more instances of another
model.
The name of the other model is pluralized when declaring a has_many
association.
For example, in an application containing authors and books. How
would be the author model declared?
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
class CreateAuthors < ActiveRecord::Migration[5.0]
def change
create_table :authors do |t|
t.string :name
t.timestamps
end
create_table :books do |t|
t.belongs_to :author, index: true
t.datetime :published_at
t.timestamps
end
end
end
The corresponding migration might look like this:
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The has_many :through Association
A many-to-many connection with another model.
The declaring model can be matched with zero or more instances of another
model by proceeding through a third model.
For example, consider a medical practice where patients make appointments to
see physicians. How should be relevant association declared?
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
class CreateAppointments < ActiveRecord::Migration[5.0]
def change
create_table :physicians do |t|
t.string :name
t.timestamps
end
create_table :patients do |t|
t.string :name
t.timestamps
end
create_table :appointments do |t|
t.belongs_to :physician, index: true
t.belongs_to :patient, index: true
t.datetime :appointment_date
t.timestamps
end
end
end
The corresponding migration might look like this:
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
physician.patients = patients
Automatic deletion of join models is direct, no destroy callbacks are
triggered.
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The has_many :through association is also useful for setting up "shortcuts"
through nested has_many associations. For example, if a document has many
sections, and a section has many paragraphs, you may sometimes want to get
a simple collection of all paragraphs in the document. You could set that up this
way:
class Document < ApplicationRecord
has_many :sections
has_many :paragraphs, through: :sections
end
class Section < ApplicationRecord
belongs_to :document
has_many :paragraphs
end
class Paragraph < ApplicationRecord
belongs_to :section
end
@document.paragraphs
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The has_one :through Association
A one-to-one connection with another model.
The declaring model can be matched with one instance of another model by
proceeding through a third model.
For example, if each supplier has one account, and each account is
associated with one account history. How should be the supplier model
could look like?
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The corresponding migration might look like this:
class CreateAccountHistories < ActiveRecord::Migration[5.0]
def change
create_table :suppliers do |t|
t.string :name
t.timestamps
end
create_table :accounts do |t|
t.belongs_to :supplier, index: true
t.string :account_number
t.timestamps
end
create_table :account_histories do |t|
t.belongs_to :account, index: true
t.integer :credit_rating
t.timestamps
end
end
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The has_and_belongs_to_many Association
A direct many-to-many connection with another model.
For example, if your application includes assemblies and parts, with each
assembly having many parts and each part appearing in many assemblies,
you could declare the models this way:
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The corresponding migration might look like this:
class CreateAssembliesAndParts < ActiveRecord::Migration[5.0]
def change
create_table :assemblies do |t|
t.string :name
t.timestamps
end
create_table :parts do |t|
t.string :part_number
t.timestamps
end
create_table :assemblies_parts, id: false do |t|
t.belongs_to :assembly, index: true
t.belongs_to :part, index: true
end
end
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Choosing Between belongs_to and has_one
If you want to set up a one-to-one relationship between two models, you'll
need to add belongs_to one, and has_one to the other. How do you know
which is which?
The distinction is in where you place the foreign key (it goes on the table
for the class declaring the belongs_to association), but you should give
some thought to the actual meaning of the data as well. The has_one
relationship says that one of something is yours - that is, that something
points back to you. For example, it makes more sense to say that a
supplier owns an account than that an account owns a supplier. This
suggests that the correct relationships are like this:
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
class Supplier < ApplicationRecord
has_one :account
end
class Account < ApplicationRecord
belongs_to :supplier
end
class CreateSuppliers < ActiveRecord::Migration[5.0]
def change
create_table :suppliers do |t|
t.string :name
t.timestamps
end
create_table :accounts do |t|
t.integer :supplier_id
t.string :account_number
t.timestamps
end
add_index :accounts, :supplier_id
end
end
The corresponding migration might look like this:
Using t.integer :supplier_id
makes the foreign key naming
obvious and explicit. In current
versions of Rails, you can
abstract away this
implementation detail by using
t.references :supplier instead.
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Choosing Between has_many :through and has_and_belongs_to_many
Rails offers two different ways to declare a many-to-many relationship between
models. The simpler way is to use has_and_belongs_to_many, which allows
you to make the association directly:
class Assembly < ApplicationRecord
has_and_belongs_to_many :parts
end
class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The second way to declare a many-to-many relationship is to use
has_many :through. This makes the association indirectly, through a join
model:
class Assembly < ApplicationRecord
has_many :manifests
has_many :parts, through: :manifests
end
class Manifest < ApplicationRecord
belongs_to :assembly
belongs_to :part
end
class Part < ApplicationRecord
has_many :manifests
has_many :assemblies, through: :manifests
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
The simplest rule of thumb is that you should set up a has_many
:through relationship if you need to work with the relationship model as
an independent entity. If you don't need to do anything with the
relationship model, it may be simpler to set up a
has_and_belongs_to_many relationship (though you'll need to
remember to create the joining table in the database).
You should use has_many :through if you need validations, callbacks
or extra attributes on the join model.
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Polymorphic Associations
A slightly more advanced twist on associations is the polymorphic
association. With polymorphic associations, a model can belong to more
than one other model, on a single association. For example, you might
have a picture model that belongs to either an employee model or a
product model. Here's how this could be declared:
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
You can think of a polymorphic belongs_to declaration as setting up an interface
that any other model can use. From an instance of the Employee model, you can
retrieve a collection of pictures: @employee.pictures.
Similarly, you can retrieve @product.pictures.
If you have an instance of the Picture model, you can get to its parent via
@picture.imageable. To make this work, you need to declare both a foreign key
column and a type column in the model that declares the polymorphic interface:
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
add_index :pictures, [:imageable_type,
:imageable_id]
end
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
This migration can be simplified by using the t.references form:
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
t.references :imageable, polymorphic: true, index: true
t.timestamps
end
end
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Self Joins
In designing a data model, you will sometimes find a model that should have
a relation to itself. For example, you may want to store all employees in a
single database model, but be able to trace relationships such as between
manager and subordinates. This situation can be modeled with self-joining
associations:
class Employee < ApplicationRecord
has_many :subordinates, class_name: "Employee",
foreign_key: "manager_id"
belongs_to :manager, class_name: "Employee"
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
With this setup, you can retrieve @employee.subordinates and
@employee.manager.
In your migrations/schema, you will add a references column to the model
itself.
class CreateEmployees < ActiveRecord::Migration[5.0]
def change
create_table :employees do |t|
t.references :manager, index: true
t.timestamps
end
end
end
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
Copyright 2016. Jyaasa Technologies.
http://jy
aasa.com
References
http://guides.rubyonrails.org/association_basics.html
Copyright 2015. Jyaasa Technologies.Copyright 2016. Jyaasa Technologies.
http://jyaasa.com

Weitere Àhnliche Inhalte

Was ist angesagt?

Messaging Standards and Systems - AMQP & RabbitMQ
Messaging Standards and Systems - AMQP & RabbitMQMessaging Standards and Systems - AMQP & RabbitMQ
Messaging Standards and Systems - AMQP & RabbitMQAll Things Open
 
Deep Dive: AWS CloudFormation
Deep Dive: AWS CloudFormationDeep Dive: AWS CloudFormation
Deep Dive: AWS CloudFormationAmazon Web Services
 
Introduction To RabbitMQ
Introduction To RabbitMQIntroduction To RabbitMQ
Introduction To RabbitMQKnoldus Inc.
 
Web Cache Poisoning
Web Cache PoisoningWeb Cache Poisoning
Web Cache PoisoningKuldeepPandya5
 
Les 5 risques les plus critiques des applications Web selon l'OWASP
Les 5 risques les plus critiques des applications Web selon l'OWASPLes 5 risques les plus critiques des applications Web selon l'OWASP
Les 5 risques les plus critiques des applications Web selon l'OWASPyaboukir
 
Flink Forward Berlin 2017: Dongwon Kim - Predictive Maintenance with Apache F...
Flink Forward Berlin 2017: Dongwon Kim - Predictive Maintenance with Apache F...Flink Forward Berlin 2017: Dongwon Kim - Predictive Maintenance with Apache F...
Flink Forward Berlin 2017: Dongwon Kim - Predictive Maintenance with Apache F...Flink Forward
 
The RabbitMQ Message Broker
The RabbitMQ Message BrokerThe RabbitMQ Message Broker
The RabbitMQ Message BrokerMartin Toshev
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?connectwebex
 
Mean Stack - An Overview
Mean Stack - An OverviewMean Stack - An Overview
Mean Stack - An OverviewNaveen Pete
 
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...Amazon Web Services
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101Itiel Shwartz
 
Cadence: The Only Workflow Platform You'll Ever Need
Cadence: The Only Workflow Platform You'll Ever NeedCadence: The Only Workflow Platform You'll Ever Need
Cadence: The Only Workflow Platform You'll Ever NeedMaxim Fateev
 
DVGA writeup
DVGA writeupDVGA writeup
DVGA writeupYu Iwama
 
Observability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringObservability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringVMware Tanzu
 
Alphorm.com Formation Microsoft 365 (MS-500) Administrateur Sécurité : Protec...
Alphorm.com Formation Microsoft 365 (MS-500) Administrateur Sécurité : Protec...Alphorm.com Formation Microsoft 365 (MS-500) Administrateur Sécurité : Protec...
Alphorm.com Formation Microsoft 365 (MS-500) Administrateur Sécurité : Protec...Alphorm
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Codemotion
 
Advanced Wi-Fi pentesting
Advanced Wi-Fi pentestingAdvanced Wi-Fi pentesting
Advanced Wi-Fi pentestingYunfei Yang
 

Was ist angesagt? (20)

Messaging Standards and Systems - AMQP & RabbitMQ
Messaging Standards and Systems - AMQP & RabbitMQMessaging Standards and Systems - AMQP & RabbitMQ
Messaging Standards and Systems - AMQP & RabbitMQ
 
Deep Dive: AWS CloudFormation
Deep Dive: AWS CloudFormationDeep Dive: AWS CloudFormation
Deep Dive: AWS CloudFormation
 
Introduction To RabbitMQ
Introduction To RabbitMQIntroduction To RabbitMQ
Introduction To RabbitMQ
 
Web Cache Poisoning
Web Cache PoisoningWeb Cache Poisoning
Web Cache Poisoning
 
Les 5 risques les plus critiques des applications Web selon l'OWASP
Les 5 risques les plus critiques des applications Web selon l'OWASPLes 5 risques les plus critiques des applications Web selon l'OWASP
Les 5 risques les plus critiques des applications Web selon l'OWASP
 
Flink Forward Berlin 2017: Dongwon Kim - Predictive Maintenance with Apache F...
Flink Forward Berlin 2017: Dongwon Kim - Predictive Maintenance with Apache F...Flink Forward Berlin 2017: Dongwon Kim - Predictive Maintenance with Apache F...
Flink Forward Berlin 2017: Dongwon Kim - Predictive Maintenance with Apache F...
 
The RabbitMQ Message Broker
The RabbitMQ Message BrokerThe RabbitMQ Message Broker
The RabbitMQ Message Broker
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?
 
Mean Stack - An Overview
Mean Stack - An OverviewMean Stack - An Overview
Mean Stack - An Overview
 
Spring integration
Spring integrationSpring integration
Spring integration
 
AMQP
AMQPAMQP
AMQP
 
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101
 
Cadence: The Only Workflow Platform You'll Ever Need
Cadence: The Only Workflow Platform You'll Ever NeedCadence: The Only Workflow Platform You'll Ever Need
Cadence: The Only Workflow Platform You'll Ever Need
 
DVGA writeup
DVGA writeupDVGA writeup
DVGA writeup
 
Observability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringObservability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with Spring
 
Alphorm.com Formation Microsoft 365 (MS-500) Administrateur Sécurité : Protec...
Alphorm.com Formation Microsoft 365 (MS-500) Administrateur Sécurité : Protec...Alphorm.com Formation Microsoft 365 (MS-500) Administrateur Sécurité : Protec...
Alphorm.com Formation Microsoft 365 (MS-500) Administrateur Sécurité : Protec...
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...
 
Advanced Wi-Fi pentesting
Advanced Wi-Fi pentestingAdvanced Wi-Fi pentesting
Advanced Wi-Fi pentesting
 

Andere mochten auch

Design Pattern:: Template Method
Design Pattern:: Template MethodDesign Pattern:: Template Method
Design Pattern:: Template MethodJyaasa Technologies
 
Scalable and Modular Architecture for CSS
Scalable and Modular Architecture for CSSScalable and Modular Architecture for CSS
Scalable and Modular Architecture for CSSJyaasa Technologies
 
BEVM ( block__element--variation -modifier)
BEVM ( block__element--variation -modifier)BEVM ( block__element--variation -modifier)
BEVM ( block__element--variation -modifier)Jyaasa Technologies
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer patternJyaasa Technologies
 
Healthcare Office Pro - Complete Overview
Healthcare Office Pro - Complete OverviewHealthcare Office Pro - Complete Overview
Healthcare Office Pro - Complete Overviewhcoffice
 
Vontade de deus
Vontade de deusVontade de deus
Vontade de deusFer Nanda
 
Predstavitev informativni dan lesarski tehnik pti 2016
Predstavitev informativni dan lesarski tehnik pti 2016Predstavitev informativni dan lesarski tehnik pti 2016
Predstavitev informativni dan lesarski tehnik pti 2016Ć C NOVO MESTO - SGLVĆ 
 
Plain text for self organisation
Plain text for self organisationPlain text for self organisation
Plain text for self organisationJyaasa Technologies
 
Design Patern::Adaptor pattern
Design Patern::Adaptor patternDesign Patern::Adaptor pattern
Design Patern::Adaptor patternJyaasa Technologies
 

Andere mochten auch (20)

Design Pattern:: Template Method
Design Pattern:: Template MethodDesign Pattern:: Template Method
Design Pattern:: Template Method
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Scalable and Modular Architecture for CSS
Scalable and Modular Architecture for CSSScalable and Modular Architecture for CSS
Scalable and Modular Architecture for CSS
 
Rails engine
Rails engineRails engine
Rails engine
 
BEVM ( block__element--variation -modifier)
BEVM ( block__element--variation -modifier)BEVM ( block__element--variation -modifier)
BEVM ( block__element--variation -modifier)
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer pattern
 
Healthcare Office Pro - Complete Overview
Healthcare Office Pro - Complete OverviewHealthcare Office Pro - Complete Overview
Healthcare Office Pro - Complete Overview
 
Inf dan 2016 gradbeni tehnik 2016
Inf dan 2016 gradbeni tehnik 2016Inf dan 2016 gradbeni tehnik 2016
Inf dan 2016 gradbeni tehnik 2016
 
Masters 3
Masters 3Masters 3
Masters 3
 
europrog avanzato
europrog avanzatoeuroprog avanzato
europrog avanzato
 
Vontade de deus
Vontade de deusVontade de deus
Vontade de deus
 
Letter of Recommendation 3
Letter of Recommendation 3Letter of Recommendation 3
Letter of Recommendation 3
 
Poklici s področja gradbeniơtva
Poklici s področja gradbeniơtvaPoklici s področja gradbeniơtva
Poklici s področja gradbeniơtva
 
Skupna predstavitev 2016
Skupna predstavitev 2016Skupna predstavitev 2016
Skupna predstavitev 2016
 
Predstavitev informativni dan lesarski tehnik pti 2016
Predstavitev informativni dan lesarski tehnik pti 2016Predstavitev informativni dan lesarski tehnik pti 2016
Predstavitev informativni dan lesarski tehnik pti 2016
 
HTML5 History
HTML5 HistoryHTML5 History
HTML5 History
 
Plain text for self organisation
Plain text for self organisationPlain text for self organisation
Plain text for self organisation
 
Command Pattern in Ruby
Command Pattern in RubyCommand Pattern in Ruby
Command Pattern in Ruby
 
Introduction of React.js
Introduction of React.jsIntroduction of React.js
Introduction of React.js
 
Design Patern::Adaptor pattern
Design Patern::Adaptor patternDesign Patern::Adaptor pattern
Design Patern::Adaptor pattern
 

Ähnlich wie Association in rails

Backward Compatibility Developer's Guide in Magento 2
Backward Compatibility Developer's Guide in Magento 2Backward Compatibility Developer's Guide in Magento 2
Backward Compatibility Developer's Guide in Magento 2Igor Miniailo
 
Rupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritanceRupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritancerupicon
 
Barcelona Salesforce Admins Group (7-May-2019)
Barcelona Salesforce Admins Group (7-May-2019)Barcelona Salesforce Admins Group (7-May-2019)
Barcelona Salesforce Admins Group (7-May-2019)Roger Borges Grilo
 
Just Enough HTML for Fatwire
Just Enough HTML for FatwireJust Enough HTML for Fatwire
Just Enough HTML for FatwireKenneth Quandt
 
Access tips access and sql part 6 dynamic reports
Access tips  access and sql part 6  dynamic reportsAccess tips  access and sql part 6  dynamic reports
Access tips access and sql part 6 dynamic reportsquest2900
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails SiddheshSiddhesh Bhobe
 
Cognos Online Training @ Adithya Elearning
Cognos Online Training @ Adithya ElearningCognos Online Training @ Adithya Elearning
Cognos Online Training @ Adithya Elearningshanmukha rao dondapati
 
Ms flow basics, troubleshooting and operational errors
Ms flow basics, troubleshooting and operational errorsMs flow basics, troubleshooting and operational errors
Ms flow basics, troubleshooting and operational errorsLearning SharePoint
 
Summer '16 Realease notes
Summer '16 Realease notesSummer '16 Realease notes
Summer '16 Realease notesaggopal1011
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
20160913_AlteryxPHX.PPTX
20160913_AlteryxPHX.PPTX20160913_AlteryxPHX.PPTX
20160913_AlteryxPHX.PPTXMichelleSaver
 
XAJA - Reverse AJAX framework
XAJA - Reverse AJAX frameworkXAJA - Reverse AJAX framework
XAJA - Reverse AJAX frameworkSri Prasanna
 
Tableau free tutorial
Tableau free tutorialTableau free tutorial
Tableau free tutorialtekslate1
 
High performance coding practices code project
High performance coding practices code projectHigh performance coding practices code project
High performance coding practices code projectPruthvi B Patil
 
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...Amazon Web Services
 
What is java script
What is java scriptWhat is java script
What is java scriptsumanbaba_73
 
Sas training in hyderabad
Sas training in hyderabadSas training in hyderabad
Sas training in hyderabadKelly Technologies
 
Introduction to whats new in css3
Introduction to whats new in css3Introduction to whats new in css3
Introduction to whats new in css3Usman Mehmood
 
The ActionScript Conference 08, Singapore - Developing ActionScript 3 Mash up...
The ActionScript Conference 08, Singapore - Developing ActionScript 3 Mash up...The ActionScript Conference 08, Singapore - Developing ActionScript 3 Mash up...
The ActionScript Conference 08, Singapore - Developing ActionScript 3 Mash up...marcocasario
 

Ähnlich wie Association in rails (20)

Backward Compatibility Developer's Guide in Magento 2
Backward Compatibility Developer's Guide in Magento 2Backward Compatibility Developer's Guide in Magento 2
Backward Compatibility Developer's Guide in Magento 2
 
Rupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritanceRupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritance
 
Barcelona Salesforce Admins Group (7-May-2019)
Barcelona Salesforce Admins Group (7-May-2019)Barcelona Salesforce Admins Group (7-May-2019)
Barcelona Salesforce Admins Group (7-May-2019)
 
Just Enough HTML for Fatwire
Just Enough HTML for FatwireJust Enough HTML for Fatwire
Just Enough HTML for Fatwire
 
Access tips access and sql part 6 dynamic reports
Access tips  access and sql part 6  dynamic reportsAccess tips  access and sql part 6  dynamic reports
Access tips access and sql part 6 dynamic reports
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
 
Cognos Online Training @ Adithya Elearning
Cognos Online Training @ Adithya ElearningCognos Online Training @ Adithya Elearning
Cognos Online Training @ Adithya Elearning
 
Ms flow basics, troubleshooting and operational errors
Ms flow basics, troubleshooting and operational errorsMs flow basics, troubleshooting and operational errors
Ms flow basics, troubleshooting and operational errors
 
Summer '16 Realease notes
Summer '16 Realease notesSummer '16 Realease notes
Summer '16 Realease notes
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
20160913_AlteryxPHX.PPTX
20160913_AlteryxPHX.PPTX20160913_AlteryxPHX.PPTX
20160913_AlteryxPHX.PPTX
 
XAJA - Reverse AJAX framework
XAJA - Reverse AJAX frameworkXAJA - Reverse AJAX framework
XAJA - Reverse AJAX framework
 
Tableau free tutorial
Tableau free tutorialTableau free tutorial
Tableau free tutorial
 
High performance coding practices code project
High performance coding practices code projectHigh performance coding practices code project
High performance coding practices code project
 
Sda 9
Sda   9Sda   9
Sda 9
 
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
Ten Tips And Tricks for Improving Your GraphQL API with AWS AppSync (MOB401) ...
 
What is java script
What is java scriptWhat is java script
What is java script
 
Sas training in hyderabad
Sas training in hyderabadSas training in hyderabad
Sas training in hyderabad
 
Introduction to whats new in css3
Introduction to whats new in css3Introduction to whats new in css3
Introduction to whats new in css3
 
The ActionScript Conference 08, Singapore - Developing ActionScript 3 Mash up...
The ActionScript Conference 08, Singapore - Developing ActionScript 3 Mash up...The ActionScript Conference 08, Singapore - Developing ActionScript 3 Mash up...
The ActionScript Conference 08, Singapore - Developing ActionScript 3 Mash up...
 

Mehr von Jyaasa Technologies

Mehr von Jyaasa Technologies (20)

Incident management with jira
Incident management with jiraIncident management with jira
Incident management with jira
 
Extreme programming practices ( xp )
Extreme programming practices ( xp ) Extreme programming practices ( xp )
Extreme programming practices ( xp )
 
The myth of 'real javascript developer'
The myth of 'real javascript developer'The myth of 'real javascript developer'
The myth of 'real javascript developer'
 
Microservices
MicroservicesMicroservices
Microservices
 
Facade pattern in rails
Facade pattern in railsFacade pattern in rails
Facade pattern in rails
 
Scrum ceromonies
Scrum ceromoniesScrum ceromonies
Scrum ceromonies
 
An introduction to bitcoin
An introduction to bitcoinAn introduction to bitcoin
An introduction to bitcoin
 
Tor network
Tor networkTor network
Tor network
 
Collective ownership in agile teams
Collective ownership in agile teamsCollective ownership in agile teams
Collective ownership in agile teams
 
Push notification
Push notificationPush notification
Push notification
 
The Design Thinking Process
The Design Thinking ProcessThe Design Thinking Process
The Design Thinking Process
 
User story
User storyUser story
User story
 
Design sprint
Design sprintDesign sprint
Design sprint
 
Data Flow Diagram
Data Flow DiagramData Flow Diagram
Data Flow Diagram
 
OKRs and Actions Overview
OKRs and Actions OverviewOKRs and Actions Overview
OKRs and Actions Overview
 
Vue.js
Vue.jsVue.js
Vue.js
 
Active record in rails 5
Active record in rails 5Active record in rails 5
Active record in rails 5
 
Web design layout pattern
Web design layout patternWeb design layout pattern
Web design layout pattern
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design Pattern
 

KĂŒrzlich hochgeladen

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

KĂŒrzlich hochgeladen (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Association in rails

  • 1. http://jy aasa.comCopyright 2016. Jyaasa Technologies. Association in rails
  • 2. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Associate Software Engineer at Jyaasa Technologies Hello ! I am Sarbada Nanda Jaiswal
  • 3. Copyright 2016. Jyaasa Technologies. http://jy aasa.com What is the association?
  • 4. Copyright 2016. Jyaasa Technologies. http://jy aasa.com In Rails, an association is a connection between two Active Record models.
  • 5. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Why associations?
  • 6. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Because they make common operations simpler and easier in your code. For example: Includes a model for authors and a model for books. Each author can have many books. The model declarations would look like:
  • 7. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Without associations With Active Record associations class Author < ApplicationRecord end class Book < ApplicationRecord end class Author < ApplicationRecord has_many :books, dependent: :destroy end class Book < ApplicationRecord belongs_to :author end @book = Book.create(published_at: Time.now, author_id: @author.id) @book = @author.books.create(published_at: Time.now) @books = Book.where(author_id: @author.id) @books.each do |book| book.destroy end @author.destroy @author.destroy
  • 8. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The Types of Associations Rails supports six types of associations: ● belongs_to ● has_one ● has_many ● has_many :through ● has_one :through ● has_and_belongs_to_many
  • 9. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The belongs_to Association A one-to-one connection with another model. Each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes authors and books, and each book can be assigned to exactly one author then how would be declared the book model?
  • 10. Copyright 2016. Jyaasa Technologies. http://jy aasa.com
  • 11. Copyright 2016. Jyaasa Technologies. http://jy aasa.com class CreateBooks < ActiveRecord::Migration[5.0] def change create_table :authors do |t| t.string :name t.timestamps end create_table :books do |t| t.belongs_to :author, index: true t.datetime :published_at t.timestamps end end end The corresponding migration might look like this:
  • 12. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The has_one Association A one-to-one connection with another model. Each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account. How would be declared the supplier model?
  • 13. Copyright 2016. Jyaasa Technologies. http://jy aasa.com
  • 14. Copyright 2016. Jyaasa Technologies. http://jy aasa.com class CreateSuppliers < ActiveRecord::Migration[5.0] def change create_table :suppliers do |t| t.string :name t.timestamps end create_table :accounts do |t| t.belongs_to :supplier, index: true t.string :account_number t.timestamps end end end The corresponding migration might look like this:
  • 15. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Depending on the use case, you might also need to create a unique index and/or a foreign key constraint on the supplier column for the accounts table. In this case, the column definition might look like this: create_table :accounts do |t| t.belongs_to :supplier, index: true, unique: true, foreign_key: true # ... end
  • 16. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The has_many Association A one-to-many connection with another model. This association on the "other side" of a belongs_to association. Each instance of the model has zero or more instances of another model. The name of the other model is pluralized when declaring a has_many association. For example, in an application containing authors and books. How would be the author model declared?
  • 17. Copyright 2016. Jyaasa Technologies. http://jy aasa.com
  • 18. Copyright 2016. Jyaasa Technologies. http://jy aasa.com class CreateAuthors < ActiveRecord::Migration[5.0] def change create_table :authors do |t| t.string :name t.timestamps end create_table :books do |t| t.belongs_to :author, index: true t.datetime :published_at t.timestamps end end end The corresponding migration might look like this:
  • 19. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The has_many :through Association A many-to-many connection with another model. The declaring model can be matched with zero or more instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. How should be relevant association declared?
  • 20. Copyright 2016. Jyaasa Technologies. http://jy aasa.com
  • 21. Copyright 2016. Jyaasa Technologies. http://jy aasa.com class CreateAppointments < ActiveRecord::Migration[5.0] def change create_table :physicians do |t| t.string :name t.timestamps end create_table :patients do |t| t.string :name t.timestamps end create_table :appointments do |t| t.belongs_to :physician, index: true t.belongs_to :patient, index: true t.datetime :appointment_date t.timestamps end end end The corresponding migration might look like this:
  • 22. Copyright 2016. Jyaasa Technologies. http://jy aasa.com physician.patients = patients Automatic deletion of join models is direct, no destroy callbacks are triggered.
  • 23. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The has_many :through association is also useful for setting up "shortcuts" through nested has_many associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way: class Document < ApplicationRecord has_many :sections has_many :paragraphs, through: :sections end class Section < ApplicationRecord belongs_to :document has_many :paragraphs end class Paragraph < ApplicationRecord belongs_to :section end @document.paragraphs
  • 24. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The has_one :through Association A one-to-one connection with another model. The declaring model can be matched with one instance of another model by proceeding through a third model. For example, if each supplier has one account, and each account is associated with one account history. How should be the supplier model could look like?
  • 25. Copyright 2016. Jyaasa Technologies. http://jy aasa.com
  • 26. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The corresponding migration might look like this: class CreateAccountHistories < ActiveRecord::Migration[5.0] def change create_table :suppliers do |t| t.string :name t.timestamps end create_table :accounts do |t| t.belongs_to :supplier, index: true t.string :account_number t.timestamps end create_table :account_histories do |t| t.belongs_to :account, index: true t.integer :credit_rating t.timestamps end end end
  • 27. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The has_and_belongs_to_many Association A direct many-to-many connection with another model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
  • 28. Copyright 2016. Jyaasa Technologies. http://jy aasa.com
  • 29. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The corresponding migration might look like this: class CreateAssembliesAndParts < ActiveRecord::Migration[5.0] def change create_table :assemblies do |t| t.string :name t.timestamps end create_table :parts do |t| t.string :part_number t.timestamps end create_table :assemblies_parts, id: false do |t| t.belongs_to :assembly, index: true t.belongs_to :part, index: true end end end
  • 30. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Choosing Between belongs_to and has_one If you want to set up a one-to-one relationship between two models, you'll need to add belongs_to one, and has_one to the other. How do you know which is which? The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association), but you should give some thought to the actual meaning of the data as well. The has_one relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
  • 31. Copyright 2016. Jyaasa Technologies. http://jy aasa.com class Supplier < ApplicationRecord has_one :account end class Account < ApplicationRecord belongs_to :supplier end class CreateSuppliers < ActiveRecord::Migration[5.0] def change create_table :suppliers do |t| t.string :name t.timestamps end create_table :accounts do |t| t.integer :supplier_id t.string :account_number t.timestamps end add_index :accounts, :supplier_id end end The corresponding migration might look like this: Using t.integer :supplier_id makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using t.references :supplier instead.
  • 32. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Choosing Between has_many :through and has_and_belongs_to_many Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use has_and_belongs_to_many, which allows you to make the association directly: class Assembly < ApplicationRecord has_and_belongs_to_many :parts end class Part < ApplicationRecord has_and_belongs_to_many :assemblies end
  • 33. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The second way to declare a many-to-many relationship is to use has_many :through. This makes the association indirectly, through a join model: class Assembly < ApplicationRecord has_many :manifests has_many :parts, through: :manifests end class Manifest < ApplicationRecord belongs_to :assembly belongs_to :part end class Part < ApplicationRecord has_many :manifests has_many :assemblies, through: :manifests end
  • 34. Copyright 2016. Jyaasa Technologies. http://jy aasa.com The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database). You should use has_many :through if you need validations, callbacks or extra attributes on the join model.
  • 35. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Polymorphic Associations A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared: class Picture < ApplicationRecord belongs_to :imageable, polymorphic: true end class Employee < ApplicationRecord has_many :pictures, as: :imageable end class Product < ApplicationRecord has_many :pictures, as: :imageable end
  • 36. Copyright 2016. Jyaasa Technologies. http://jy aasa.com You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use. From an instance of the Employee model, you can retrieve a collection of pictures: @employee.pictures. Similarly, you can retrieve @product.pictures. If you have an instance of the Picture model, you can get to its parent via @picture.imageable. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface: class CreatePictures < ActiveRecord::Migration[5.0] def change create_table :pictures do |t| t.string :name t.integer :imageable_id t.string :imageable_type t.timestamps end add_index :pictures, [:imageable_type, :imageable_id] end end
  • 37. Copyright 2016. Jyaasa Technologies. http://jy aasa.com This migration can be simplified by using the t.references form: class CreatePictures < ActiveRecord::Migration[5.0] def change create_table :pictures do |t| t.string :name t.references :imageable, polymorphic: true, index: true t.timestamps end end end
  • 38. Copyright 2016. Jyaasa Technologies. http://jy aasa.com
  • 39. Copyright 2016. Jyaasa Technologies. http://jy aasa.com Self Joins In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations: class Employee < ApplicationRecord has_many :subordinates, class_name: "Employee", foreign_key: "manager_id" belongs_to :manager, class_name: "Employee" end
  • 40. Copyright 2016. Jyaasa Technologies. http://jy aasa.com With this setup, you can retrieve @employee.subordinates and @employee.manager. In your migrations/schema, you will add a references column to the model itself. class CreateEmployees < ActiveRecord::Migration[5.0] def change create_table :employees do |t| t.references :manager, index: true t.timestamps end end end
  • 41. Copyright 2016. Jyaasa Technologies. http://jy aasa.com
  • 42. Copyright 2016. Jyaasa Technologies. http://jy aasa.com References http://guides.rubyonrails.org/association_basics.html
  • 43. Copyright 2015. Jyaasa Technologies.Copyright 2016. Jyaasa Technologies. http://jyaasa.com