SlideShare a Scribd company logo
1 of 58
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
The has_one Association
has_one association also sets up a one-to-one connection with another
model
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.
The has_many :through Association
a many-to-many connection
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:
The has_and_belongs_to_many Association
creates a direct many-to-many connection
with another model, with no intervening
model.
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
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

What's hot

Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptxvishal choudhary
 
ASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CSASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CStutorialsruby
 
Hibernate Mapping
Hibernate MappingHibernate Mapping
Hibernate MappingInnovationM
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
VIPER Architecture
VIPER ArchitectureVIPER Architecture
VIPER ArchitectureAhmed Lotfy
 
Design Summit - Navigating the ManageIQ Object Model - Brad Ascar
Design Summit - Navigating the ManageIQ Object Model - Brad AscarDesign Summit - Navigating the ManageIQ Object Model - Brad Ascar
Design Summit - Navigating the ManageIQ Object Model - Brad AscarManageIQ
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blogPierre Sudron
 
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 PatternRobert Pankowecki
 
Best Practices for Magento Debugging
Best Practices for Magento Debugging Best Practices for Magento Debugging
Best Practices for Magento Debugging varien
 
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...Learnosity
 

What's hot (18)

Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
ASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CSASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CS
 
Hibernate Mapping
Hibernate MappingHibernate Mapping
Hibernate Mapping
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Backendless apps
Backendless appsBackendless apps
Backendless apps
 
Actionview
ActionviewActionview
Actionview
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
VIPER Architecture
VIPER ArchitectureVIPER Architecture
VIPER Architecture
 
Design Summit - Navigating the ManageIQ Object Model - Brad Ascar
Design Summit - Navigating the ManageIQ Object Model - Brad AscarDesign Summit - Navigating the ManageIQ Object Model - Brad Ascar
Design Summit - Navigating the ManageIQ Object Model - Brad Ascar
 
Vue.js 101
Vue.js 101Vue.js 101
Vue.js 101
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
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
 
Best Practices for Magento Debugging
Best Practices for Magento Debugging Best Practices for Magento Debugging
Best Practices for Magento Debugging
 
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
 

Similar to Active record(1)

RubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendallRubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendalltutorialsruby
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails Mohit Jain
 
Intro to Rails ActiveRecord
Intro to Rails ActiveRecordIntro to Rails ActiveRecord
Intro to Rails ActiveRecordMark Menard
 
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...Coupa Software
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on RailsMark Menard
 
Lessons from running AppSync in prod
Lessons from running AppSync in prodLessons from running AppSync in prod
Lessons from running AppSync in prodYan Cui
 
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 30fiyuer
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le WagonAlex Benoit
 
Desenvolvimento web com Ruby on Rails (extras)
Desenvolvimento web com Ruby on Rails (extras)Desenvolvimento web com Ruby on Rails (extras)
Desenvolvimento web com Ruby on Rails (extras)Joao Lucas Santana
 
Timothy N. Tsvetkov, Rails 3.1
Timothy N. Tsvetkov, Rails 3.1Timothy N. Tsvetkov, Rails 3.1
Timothy N. Tsvetkov, Rails 3.1Evil Martians
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperfNew Relic
 
Spca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesSpca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesNCCOMMS
 
Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkOdoo
 
Connecting your Python App to OpenERP through OOOP
Connecting your Python App to OpenERP through OOOPConnecting your Python App to OpenERP through OOOP
Connecting your Python App to OpenERP through OOOPraimonesteve
 
Model of the colossus @ Rupy Brazil 2013
Model of the colossus @ Rupy Brazil 2013 Model of the colossus @ Rupy Brazil 2013
Model of the colossus @ Rupy Brazil 2013 Mauro George
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember Chandra Sekar
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with RailsJames Gray
 

Similar to Active record(1) (20)

RubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendallRubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendall
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
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...
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on Rails
 
Lessons from running AppSync in prod
Lessons from running AppSync in prodLessons from running AppSync in prod
Lessons from running AppSync in prod
 
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
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le Wagon
 
Desenvolvimento web com Ruby on Rails (extras)
Desenvolvimento web com Ruby on Rails (extras)Desenvolvimento web com Ruby on Rails (extras)
Desenvolvimento web com Ruby on Rails (extras)
 
Timothy N. Tsvetkov, Rails 3.1
Timothy N. Tsvetkov, Rails 3.1Timothy N. Tsvetkov, Rails 3.1
Timothy N. Tsvetkov, Rails 3.1
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperf
 
Spca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesSpca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_libraries
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
 
Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo Framework
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
Connecting your Python App to OpenERP through OOOP
Connecting your Python App to OpenERP through OOOPConnecting your Python App to OpenERP through OOOP
Connecting your Python App to OpenERP through OOOP
 
Model of the colossus @ Rupy Brazil 2013
Model of the colossus @ Rupy Brazil 2013 Model of the colossus @ Rupy Brazil 2013
Model of the colossus @ Rupy Brazil 2013
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
 
Create Components in TomatoCMS
Create Components in TomatoCMSCreate Components in TomatoCMS
Create Components in TomatoCMS
 

Recently uploaded

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 

Recently uploaded (20)

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 

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
  • 14.
  • 15. The has_one Association has_one association also sets up a one-to-one connection with another model
  • 16.
  • 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.
  • 19.
  • 20. The has_many :through Association a many-to-many connection
  • 21.
  • 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:
  • 26.
  • 27. The has_and_belongs_to_many Association creates a direct many-to-many connection with another model, with no intervening model.
  • 28.
  • 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
  • 53.
  • 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