SlideShare uma empresa Scribd logo
1 de 63
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Mongo DB schema design patterns
Mongo DB schema design patternsMongo DB schema design patterns
Mongo DB schema design patternsjoergreichert
 
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...MongoDB
 
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 presentationMurat Çakal
 
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 ExamplesMike Friedman
 
MongoDB Schema Design
MongoDB Schema DesignMongoDB Schema Design
MongoDB Schema DesignAlex Litvinok
 
Data Modeling for the Real World
Data Modeling for the Real WorldData Modeling for the Real World
Data Modeling for the Real WorldMike Friedman
 
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 MongoDBUwe Printz
 
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 2011Steven Francia
 
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 DocumentsMongoDB
 
MongoDB Advanced Schema Design - Inboxes
MongoDB Advanced Schema Design - InboxesMongoDB Advanced Schema Design - Inboxes
MongoDB Advanced Schema Design - InboxesJared Rosoff
 
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 WorldMongoDB
 
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 ModelingDATAVERSITY
 
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 Norberto Leite
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleMongoDB
 
Dealing with Azure Cosmos DB
Dealing with Azure Cosmos DBDealing with Azure Cosmos DB
Dealing with Azure Cosmos DBMihail Mateev
 
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 DocumentsMongoDB
 
Webinar: Schema Design
Webinar: Schema DesignWebinar: Schema Design
Webinar: Schema DesignMongoDB
 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDBMongoDB
 

Mais procurados (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
 

Semelhante a ActiveRecord vs Mongoid

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 dbMongoDB
 
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 MongoMapperGiordano Scalzo
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling rogerbodamer
 
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 MongoDBMongoDB
 
Api's and ember js
Api's and ember jsApi's and ember js
Api's and ember jsEdwin Cruz
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012Yaqi Zhao
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDBNate Abele
 
Mongodb intro
Mongodb introMongodb intro
Mongodb introchristkv
 
Schema design
Schema designSchema design
Schema designchristkv
 
Managing Social Content with MongoDB
Managing Social Content with MongoDBManaging Social Content with MongoDB
Managing Social Content with MongoDBMongoDB
 
Aggregation Framework MongoDB Days Munich
Aggregation Framework MongoDB Days MunichAggregation Framework MongoDB Days Munich
Aggregation Framework MongoDB Days MunichNorberto Leite
 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDBNorberto Leite
 
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 TeamsMongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBAlex Bilbie
 
MongoDB + node.js で作るソーシャルゲーム
MongoDB + node.js で作るソーシャルゲームMongoDB + node.js で作るソーシャルゲーム
MongoDB + node.js で作るソーシャルゲームSuguru Namura
 
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 DocumentsJoe Drumgoole
 
Webinar: Building Your First App
Webinar: Building Your First AppWebinar: Building Your First App
Webinar: Building Your First AppMongoDB
 

Semelhante 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
 

Mais de Ivan Nemytchenko

Breaking Bad Habits with GitLab CI
Breaking Bad Habits with GitLab CIBreaking Bad Habits with GitLab CI
Breaking Bad Habits with GitLab CIIvan Nemytchenko
 
How to stop being Rails Developer
How to stop being Rails DeveloperHow to stop being Rails Developer
How to stop being Rails DeveloperIvan 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 developersIvan Nemytchenko
 
Breaking bad habits with GitLab CI
Breaking bad habits with GitLab CIBreaking bad habits with GitLab CI
Breaking bad habits with GitLab CIIvan Nemytchenko
 
Lean Poker in Lviv announce
Lean Poker in Lviv announceLean Poker in Lviv announce
Lean Poker in Lviv announceIvan Nemytchenko
 
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. Ivan Nemytchenko
 
Опыт организации удаленной стажировки для рубистов
Опыт организации удаленной стажировки для рубистовОпыт организации удаленной стажировки для рубистов
Опыт организации удаленной стажировки для рубистовIvan Nemytchenko
 
Principles. Misunderstood. Applied
Principles. Misunderstood. AppliedPrinciples. Misunderstood. Applied
Principles. Misunderstood. AppliedIvan Nemytchenko
 
From Rails-way to modular architecture
From Rails-way to modular architectureFrom Rails-way to modular architecture
From Rails-way to modular architectureIvan Nemytchenko
 
Рассказ про RedDotRubyConf 2014
Рассказ про RedDotRubyConf 2014Рассказ про RedDotRubyConf 2014
Рассказ про RedDotRubyConf 2014Ivan 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 architectureIvan 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 - язык для продвинутой генерации JSONIvan Nemytchenko
 

Mais 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

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
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 WorkerThousandEyes
 

Último (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 

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