SlideShare una empresa de Scribd logo
1 de 63
Descargar para leer sin conexión
ActiveRecord vs Mongoid

      Иван Немытченко, 7bits, Омск
PHP → Ruby on Rails →freelance →
JazzCloud → Tulp → 7bits
2007 - Ruby on Rails
2007 - Ruby on Rails
2008 - HAML/SASS
2007 - Ruby on Rails
2008 - HAML/SASS
2010 - Coffeescript
2007 - Ruby on Rails
2008 - HAML/SASS
2010 - Coffeescript
2010 - Tequila → RABL
2007 - Ruby on Rails
2008 - HAML/SASS
2010 - Coffeescript
2010 - Tequila → RABL
2011 - Tulp
2012 - MongoDB
2007 - Ruby on Rails
2008 - HAML/SASS
2010 - Coffeescript
2010 - Tequila → RABL
2012 - ActiveRecord vs Mongoid
MongoDB
MongoDB is a scalable, high-performance, open
“   source NoSQL database
                          ”
НЕТ ТРАНЗАКЦИЙ
НЕТ ТРАНЗАКЦИЙ
НЕТ ДЖОЙНОВ
Таблицы → Коллекции
Таблицы → Коллекции
Строки → Документы
{ "_id" : ObjectId( "4fb8dd1324ec7c1344000003" ),
  "agent" : "Ivan Nemytchenko",
  "challenge" : "Introduce MongoDB documents",
  "status" : "accepted"
  }
{ "_id" : ObjectId( "4fb8dd1324ec7c1344000003" ),
  "agent" : "Ivan Nemytchenko",
  "missions": [
    { "challenge" : "Introduce MongoDB documents",
       "status" : "done"
    },
    { "challenge" : "Tell the truth about MongoDB",
       "status" : "considering"
    }
  ]
  }
Таблицы → Коллекции
Строки → Документы
Индексы → Индексы
Mongoid
Object Document Mapper
“   The philosophy of Mongoid is to provide a
    familiar API to Ruby developers who have been
    using Active Record or Data Mapper, while
    leveraging the power of MongoDB's schemaless
    and performant document-based design, dynamic
    queries, and atomic modifier operations
                                           ”
                             Durran Jordan, автор Mongoid
Связи
has_many
 has_one
belongs_to
has_many
       has_one
      belongs_to

has_and_belongs_to_many
has_many
                      has_one
                     belongs_to

               has_and_belongs_to_many


        address:                organization:
{organization_ids:[1,2,3]} {address_ids:[5,3,1,10]}
has_many
       has_one
      belongs_to

has_and_belongs_to_many

   has_many :through
has_many
       has_one
      belongs_to

has_and_belongs_to_many

   has_many :through
has_many
       has_one
      belongs_to

has_and_belongs_to_many

   has_many :through

     embeds_many
      embeds_one
     embedded_in
Lets Practice!
class Contact                              class Place
  include Mongoid::Document                  include Mongoid::Document
  field :type                                embeds_many :contacts
  field :value                             end
  embedded_in :place
end
place.contacts << Contact.new(:type => "phone", :value => "32-14-90")
place.contacts << Contact.new(:type => "email", :value => "omskps1@rosinter.ru")
place.save
{ "_id" : 1,
  "name" : "Планета Суши"
  "contacts" : [
    { "_id" : 1,
      "type" : "phone", "value" : "32-14-90" },
    { "_id" : 2,
      "type" : "email", "value" : "omskps1@rosinter.ru" }
    ]
  }
{ "_id" : 1,
  "name" : "Планета Суши"
  "contacts" : [
    { "_id" : 1,
      "_type" : "phone", "value" : "32-14-90" },
    { "_id" : 2,
      "_type" : "email", "value" : "omskps1@rosinter.ru" }
    ]
  }
class Contact
                                  class Place
  include Mongoid::Document
                                    include Mongoid::Document
  field :type
                                    embeds_many :contacts
  field :value
                                  end
  embedded_in :place
end                              class Email < Contact
                                 end
                                  class Phone < Contact
                                  end

place.contacts << Phone.new(:value => "32-14-90")
place.contacts << Email.new(:value => "omskps1@rosinter.ru")
place.save
Rating                   RatingType
  embedded_in :place       embedded_in :category

Place                    Category
  embeds_many :ratings     embeds_many :rating_types
Place
{ "_id" : 1,
  "name" : "Планета Суши"
  "ratings" : [
    { "_id":1, "type":"Качество обслуживания", "value":4 },
    { "_id":2, "type":"Чистота", "value":5 } ]
  }

Rating                          RatingType
  embedded_in :place              embedded_in :category

Place                           Category
  embeds_many :ratings            embeds_many :rating_types
Place
{ "_id" : 1,
  "name" : "Планета Суши"
  "ratings" : [
    { "_id":1, "type":"Качество обслуживания", "value":4 },
    { "_id":2, "type":"Чистота", "value":5 } ]
  }
                                                      Category
{ "_id" : 1,
  "name" : "Рестораны"
  "rating_types" : ["Качество обслуживания", "Чистота"]
  }

Rating                          RatingType
  embedded_in :place              embedded_in :category

Place                           Category
  embeds_many :ratings            embeds_many :rating_types
Place
{ "_id" : 1,
  "name" : "Планета Суши"
  "ratings" : [
    { "_id":1, "type":"Качество обслуживания", "value":4 },
    { "_id":2, "type":"Чистота", "value":5 } ]
  }
                                                      Category
{ "_id" : 1,
  "name" : "Рестораны"
  "rating_types" : ["Качество обслуживания", "Чистота"]
  }




Place.where(:"ratings.type"=>"Чистота", :"ratings.value.gt"=>3)
Answer
  embedded_in :question

Question                   Property
  embedded_in :category      embedded_in :place
  embeds_many :answers       field :question
                             field :answer
Category                   Place
  embeds_many :questions     embeds_many :properties
>> category.questions << Question.new(:value =>
'WiFi', :answers => ['есть', 'нету'])

>> place.properties << Property.new(:question =>
'WiFi', :answer => 'есть')
Place
{ "_id" : 1,
  "name" : ".."
  "contacts" : [
    { "_type" : "phone", "value" : "32-14-90" },
    { "_type" : "email", "value" : "..." }],
  "ratings" : [
    { "type" : "..", "value" : ".." },
    { "type" : "..", "value" : ".." }],
  "properties" : [
    { "question" : "..", "answer" : ".." }],
  "categories" : ["..", ".."],
  "review_ids" : [12, 34, 56]
  }
                                                      Review
{ "_id" : 12,
  "user_id" : 16,
  "place_id" : 1,
  "body" : “..”,
  "comments" : [
    { "body" : "..",   "user_id" : 1, "user_name" : ".." },
    { "body" : "..",   "user_id" : 5, "user_name" : ".."}],
  "ratings" : [
    { "type" : "..",   "value" : ".." },
    { "type" : "..",   "value" : ".." }]
}
Place            Review
  Contacts        AuthorSummary
  Ratings         Ratings
  Properties      Comments
  Categories →
                 User
 Category         Reviews →
  RatingTypes
  Questions
   Answers
To embed or not to embed?

      Соотношение запись/чтение
        Жизненный цикл объекта
   Так ли важна целостность данных?
Extra Stuff
GridFS

     CarrierWave.configure do |config|
       config.storage = :grid_fs
       config.grid_fs_connection = Mongoid.database
       config.grid_fs_host = app_config['domain']
       config.grid_fs_access_url = "/gridfs"
     end


     class PhotoUploader < CarrierWave::Uploader::Base
       storage :grid_fs
     end




gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
Локализация
class Person
  include Mongoid::Document

  field :first_name, :localize => true
  field :last_name, :localize => true
end




{ "_id" : 1,
   "first_name" : { "ru" : "Иван" },
   "last_name" : { "ru" : "Немытченко" }
 }
Полный фарш
class Person
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Versioning
  include Mongoid::Paranoia

  field :first_name
  field :last_name
  key :first_name, :last_name
end
Гибридные приложения

class TodoLog                        class Todo < ActiveRecord::Base
  include Mongoid::Document            after_create :create_log
  field :todo_id, :type => Integer     after_update :create_log
  field :title, :type => String
  field :done, :type => Boolean        private
end                                    def create_log
                                         TodoLog.create(
                                           :title => title,
                                           :done => !!done,
                                           :todo_id => id
                                         )
                                       end
                                     end




    https://github.com/a2ikm/activerecord-and-mongoid-sample
Анти-mongoid


    This tool exposes simplicity and power of
“   MongoDB and leverages its differences
                                               ”
                        Алексей Петрушин, автор MongoModel




http://alexeypetrushin.github.com/mongodb_model/index.html
Спасибо. Давайте поговорим.




         @inem
       inem@bk.ru

Más contenido relacionado

La actualidad más candente

Building web applications with mongo db presentation
Building web applications with mongo db presentationBuilding web applications with mongo db presentation
Building web applications with mongo db presentation
Murat Çakal
 
MongoDB Schema Design
MongoDB Schema DesignMongoDB Schema Design
MongoDB Schema Design
Alex Litvinok
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling
DATAVERSITY
 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDB
MongoDB
 

La actualidad más candente (18)

Mongo DB schema design patterns
Mongo DB schema design patternsMongo DB schema design patterns
Mongo DB schema design patterns
 
MongoDB San Francisco 2013: Data Modeling Examples From the Real World presen...
MongoDB San Francisco 2013: Data Modeling Examples From the Real World presen...MongoDB San Francisco 2013: Data Modeling Examples From the Real World presen...
MongoDB San Francisco 2013: Data Modeling Examples From the Real World presen...
 
Building web applications with mongo db presentation
Building web applications with mongo db presentationBuilding web applications with mongo db presentation
Building web applications with mongo db presentation
 
MongoDB Schema Design: Four Real-World Examples
MongoDB Schema Design: Four Real-World ExamplesMongoDB Schema Design: Four Real-World Examples
MongoDB Schema Design: Four Real-World Examples
 
MongoDB Schema Design
MongoDB Schema DesignMongoDB Schema Design
MongoDB Schema Design
 
Data Modeling for the Real World
Data Modeling for the Real WorldData Modeling for the Real World
Data Modeling for the Real World
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDB
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011
 
Webinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in DocumentsWebinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in Documents
 
MongoDB Advanced Schema Design - Inboxes
MongoDB Advanced Schema Design - InboxesMongoDB Advanced Schema Design - Inboxes
MongoDB Advanced Schema Design - Inboxes
 
Webinar: Data Modeling Examples in the Real World
Webinar: Data Modeling Examples in the Real WorldWebinar: Data Modeling Examples in the Real World
Webinar: Data Modeling Examples in the Real World
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You Scale
 
Dealing with Azure Cosmos DB
Dealing with Azure Cosmos DBDealing with Azure Cosmos DB
Dealing with Azure Cosmos DB
 
Back to Basics Webinar 3: Schema Design Thinking in Documents
 Back to Basics Webinar 3: Schema Design Thinking in Documents Back to Basics Webinar 3: Schema Design Thinking in Documents
Back to Basics Webinar 3: Schema Design Thinking in Documents
 
Webinar: Schema Design
Webinar: Schema DesignWebinar: Schema Design
Webinar: Schema Design
 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDB
 

Similar a ActiveRecord vs Mongoid

Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.
Ravi Teja
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012
Yaqi Zhao
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Alex Bilbie
 

Similar a ActiveRecord vs Mongoid (20)

Building your first app with mongo db
Building your first app with mongo dbBuilding your first app with mongo db
Building your first app with mongo db
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
 
Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.
 
Mongo db presentation
Mongo db presentationMongo db presentation
Mongo db presentation
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Api's and ember js
Api's and ember jsApi's and ember js
Api's and ember js
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
 
Mongodb intro
Mongodb introMongodb intro
Mongodb intro
 
Schema design
Schema designSchema design
Schema design
 
Managing Social Content with MongoDB
Managing Social Content with MongoDBManaging Social Content with MongoDB
Managing Social Content with MongoDB
 
Aggregation Framework MongoDB Days Munich
Aggregation Framework MongoDB Days MunichAggregation Framework MongoDB Days Munich
Aggregation Framework MongoDB Days Munich
 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB + node.js で作るソーシャルゲーム
MongoDB + node.js で作るソーシャルゲームMongoDB + node.js で作るソーシャルゲーム
MongoDB + node.js で作るソーシャルゲーム
 
Back to Basics Webinar 3 - Thinking in Documents
Back to Basics Webinar 3 - Thinking in DocumentsBack to Basics Webinar 3 - Thinking in Documents
Back to Basics Webinar 3 - Thinking in Documents
 
Webinar: Building Your First App
Webinar: Building Your First AppWebinar: Building Your First App
Webinar: Building Your First App
 

Más de Ivan Nemytchenko

What I Have Learned from Organizing Remote Internship for Ruby developers
What I Have Learned from Organizing Remote Internship for Ruby developersWhat I Have Learned from Organizing Remote Internship for Ruby developers
What I Have Learned from Organizing Remote Internship for Ruby developers
Ivan Nemytchenko
 
Рефакторинг rails-приложения. С чего начать?
Рефакторинг rails-приложения. С чего начать?Рефакторинг rails-приложения. С чего начать?
Рефакторинг rails-приложения. С чего начать?
Ivan Nemytchenko
 
Different approaches to ruby web applications architecture
Different approaches to ruby web applications architectureDifferent approaches to ruby web applications architecture
Different approaches to ruby web applications architecture
Ivan Nemytchenko
 
От Rails-way к модульной архитектуре
От Rails-way к модульной архитектуреОт Rails-way к модульной архитектуре
От Rails-way к модульной архитектуре
Ivan Nemytchenko
 
Coffescript - счастье для javascript-разработчика
Coffescript - счастье для javascript-разработчикаCoffescript - счастье для javascript-разработчика
Coffescript - счастье для javascript-разработчика
Ivan Nemytchenko
 
Tequila - язык для продвинутой генерации JSON
Tequila - язык для продвинутой генерации JSONTequila - язык для продвинутой генерации JSON
Tequila - язык для продвинутой генерации JSON
Ivan Nemytchenko
 

Más de Ivan Nemytchenko (15)

Breaking Bad Habits with GitLab CI
Breaking Bad Habits with GitLab CIBreaking Bad Habits with GitLab CI
Breaking Bad Habits with GitLab CI
 
How to stop being Rails Developer
How to stop being Rails DeveloperHow to stop being Rails Developer
How to stop being Rails Developer
 
What I Have Learned from Organizing Remote Internship for Ruby developers
What I Have Learned from Organizing Remote Internship for Ruby developersWhat I Have Learned from Organizing Remote Internship for Ruby developers
What I Have Learned from Organizing Remote Internship for Ruby developers
 
Breaking bad habits with GitLab CI
Breaking bad habits with GitLab CIBreaking bad habits with GitLab CI
Breaking bad habits with GitLab CI
 
Lean Poker in Lviv announce
Lean Poker in Lviv announceLean Poker in Lviv announce
Lean Poker in Lviv announce
 
How to use any static site generator with GitLab Pages.
How to use any static site generator with GitLab Pages. How to use any static site generator with GitLab Pages.
How to use any static site generator with GitLab Pages.
 
Опыт организации удаленной стажировки для рубистов
Опыт организации удаленной стажировки для рубистовОпыт организации удаленной стажировки для рубистов
Опыт организации удаленной стажировки для рубистов
 
Principles. Misunderstood. Applied
Principles. Misunderstood. AppliedPrinciples. Misunderstood. Applied
Principles. Misunderstood. Applied
 
From Rails-way to modular architecture
From Rails-way to modular architectureFrom Rails-way to modular architecture
From Rails-way to modular architecture
 
Рассказ про RedDotRubyConf 2014
Рассказ про RedDotRubyConf 2014Рассказ про RedDotRubyConf 2014
Рассказ про RedDotRubyConf 2014
 
Рефакторинг rails-приложения. С чего начать?
Рефакторинг rails-приложения. С чего начать?Рефакторинг rails-приложения. С чего начать?
Рефакторинг rails-приложения. С чего начать?
 
Different approaches to ruby web applications architecture
Different approaches to ruby web applications architectureDifferent approaches to ruby web applications architecture
Different approaches to ruby web applications architecture
 
От Rails-way к модульной архитектуре
От Rails-way к модульной архитектуреОт Rails-way к модульной архитектуре
От Rails-way к модульной архитектуре
 
Coffescript - счастье для javascript-разработчика
Coffescript - счастье для javascript-разработчикаCoffescript - счастье для javascript-разработчика
Coffescript - счастье для javascript-разработчика
 
Tequila - язык для продвинутой генерации JSON
Tequila - язык для продвинутой генерации JSONTequila - язык для продвинутой генерации JSON
Tequila - язык для продвинутой генерации JSON
 

Último

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
vu2urc
 

Último (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 

ActiveRecord vs Mongoid

  • 1. ActiveRecord vs Mongoid Иван Немытченко, 7bits, Омск
  • 2. PHP → Ruby on Rails →freelance → JazzCloud → Tulp → 7bits
  • 3. 2007 - Ruby on Rails
  • 4. 2007 - Ruby on Rails 2008 - HAML/SASS
  • 5. 2007 - Ruby on Rails 2008 - HAML/SASS 2010 - Coffeescript
  • 6. 2007 - Ruby on Rails 2008 - HAML/SASS 2010 - Coffeescript 2010 - Tequila → RABL
  • 7. 2007 - Ruby on Rails 2008 - HAML/SASS 2010 - Coffeescript 2010 - Tequila → RABL 2011 - Tulp 2012 - MongoDB
  • 8. 2007 - Ruby on Rails 2008 - HAML/SASS 2010 - Coffeescript 2010 - Tequila → RABL 2012 - ActiveRecord vs Mongoid
  • 10. MongoDB is a scalable, high-performance, open “ source NoSQL database ”
  • 15. { "_id" : ObjectId( "4fb8dd1324ec7c1344000003" ), "agent" : "Ivan Nemytchenko", "challenge" : "Introduce MongoDB documents", "status" : "accepted" }
  • 16. { "_id" : ObjectId( "4fb8dd1324ec7c1344000003" ), "agent" : "Ivan Nemytchenko", "missions": [ { "challenge" : "Introduce MongoDB documents", "status" : "done" }, { "challenge" : "Tell the truth about MongoDB", "status" : "considering" } ] }
  • 17. Таблицы → Коллекции Строки → Документы Индексы → Индексы
  • 19. The philosophy of Mongoid is to provide a familiar API to Ruby developers who have been using Active Record or Data Mapper, while leveraging the power of MongoDB's schemaless and performant document-based design, dynamic queries, and atomic modifier operations ” Durran Jordan, автор Mongoid
  • 22. has_many has_one belongs_to has_and_belongs_to_many
  • 23. has_many has_one belongs_to has_and_belongs_to_many address: organization: {organization_ids:[1,2,3]} {address_ids:[5,3,1,10]}
  • 24. has_many has_one belongs_to has_and_belongs_to_many has_many :through
  • 25. has_many has_one belongs_to has_and_belongs_to_many has_many :through
  • 26. has_many has_one belongs_to has_and_belongs_to_many has_many :through embeds_many embeds_one embedded_in
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35. class Contact class Place include Mongoid::Document include Mongoid::Document field :type embeds_many :contacts field :value end embedded_in :place end place.contacts << Contact.new(:type => "phone", :value => "32-14-90") place.contacts << Contact.new(:type => "email", :value => "omskps1@rosinter.ru") place.save
  • 36. { "_id" : 1, "name" : "Планета Суши" "contacts" : [ { "_id" : 1, "type" : "phone", "value" : "32-14-90" }, { "_id" : 2, "type" : "email", "value" : "omskps1@rosinter.ru" } ] }
  • 37. { "_id" : 1, "name" : "Планета Суши" "contacts" : [ { "_id" : 1, "_type" : "phone", "value" : "32-14-90" }, { "_id" : 2, "_type" : "email", "value" : "omskps1@rosinter.ru" } ] }
  • 38. class Contact class Place include Mongoid::Document include Mongoid::Document field :type embeds_many :contacts field :value end embedded_in :place end class Email < Contact end class Phone < Contact end place.contacts << Phone.new(:value => "32-14-90") place.contacts << Email.new(:value => "omskps1@rosinter.ru") place.save
  • 39.
  • 40.
  • 41.
  • 42. Rating RatingType embedded_in :place embedded_in :category Place Category embeds_many :ratings embeds_many :rating_types
  • 43. Place { "_id" : 1, "name" : "Планета Суши" "ratings" : [ { "_id":1, "type":"Качество обслуживания", "value":4 }, { "_id":2, "type":"Чистота", "value":5 } ] } Rating RatingType embedded_in :place embedded_in :category Place Category embeds_many :ratings embeds_many :rating_types
  • 44. Place { "_id" : 1, "name" : "Планета Суши" "ratings" : [ { "_id":1, "type":"Качество обслуживания", "value":4 }, { "_id":2, "type":"Чистота", "value":5 } ] } Category { "_id" : 1, "name" : "Рестораны" "rating_types" : ["Качество обслуживания", "Чистота"] } Rating RatingType embedded_in :place embedded_in :category Place Category embeds_many :ratings embeds_many :rating_types
  • 45. Place { "_id" : 1, "name" : "Планета Суши" "ratings" : [ { "_id":1, "type":"Качество обслуживания", "value":4 }, { "_id":2, "type":"Чистота", "value":5 } ] } Category { "_id" : 1, "name" : "Рестораны" "rating_types" : ["Качество обслуживания", "Чистота"] } Place.where(:"ratings.type"=>"Чистота", :"ratings.value.gt"=>3)
  • 46.
  • 47.
  • 48.
  • 49. Answer embedded_in :question Question Property embedded_in :category embedded_in :place embeds_many :answers field :question field :answer Category Place embeds_many :questions embeds_many :properties
  • 50. >> category.questions << Question.new(:value => 'WiFi', :answers => ['есть', 'нету']) >> place.properties << Property.new(:question => 'WiFi', :answer => 'есть')
  • 51.
  • 52.
  • 53.
  • 54. Place { "_id" : 1, "name" : ".." "contacts" : [ { "_type" : "phone", "value" : "32-14-90" }, { "_type" : "email", "value" : "..." }], "ratings" : [ { "type" : "..", "value" : ".." }, { "type" : "..", "value" : ".." }], "properties" : [ { "question" : "..", "answer" : ".." }], "categories" : ["..", ".."], "review_ids" : [12, 34, 56] } Review { "_id" : 12, "user_id" : 16, "place_id" : 1, "body" : “..”, "comments" : [ { "body" : "..", "user_id" : 1, "user_name" : ".." }, { "body" : "..", "user_id" : 5, "user_name" : ".."}], "ratings" : [ { "type" : "..", "value" : ".." }, { "type" : "..", "value" : ".." }] }
  • 55. Place Review Contacts AuthorSummary Ratings Ratings Properties Comments Categories → User Category Reviews → RatingTypes Questions Answers
  • 56. To embed or not to embed? Соотношение запись/чтение Жизненный цикл объекта Так ли важна целостность данных?
  • 58. GridFS CarrierWave.configure do |config| config.storage = :grid_fs config.grid_fs_connection = Mongoid.database config.grid_fs_host = app_config['domain'] config.grid_fs_access_url = "/gridfs" end class PhotoUploader < CarrierWave::Uploader::Base storage :grid_fs end gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
  • 59. Локализация class Person include Mongoid::Document field :first_name, :localize => true field :last_name, :localize => true end { "_id" : 1, "first_name" : { "ru" : "Иван" }, "last_name" : { "ru" : "Немытченко" } }
  • 60. Полный фарш class Person include Mongoid::Document include Mongoid::Timestamps include Mongoid::Versioning include Mongoid::Paranoia field :first_name field :last_name key :first_name, :last_name end
  • 61. Гибридные приложения class TodoLog class Todo < ActiveRecord::Base include Mongoid::Document after_create :create_log field :todo_id, :type => Integer after_update :create_log field :title, :type => String field :done, :type => Boolean private end def create_log TodoLog.create( :title => title, :done => !!done, :todo_id => id ) end end https://github.com/a2ikm/activerecord-and-mongoid-sample
  • 62. Анти-mongoid This tool exposes simplicity and power of “ MongoDB and leverages its differences ” Алексей Петрушин, автор MongoModel http://alexeypetrushin.github.com/mongodb_model/index.html