ActiveRecord vs Mongoid      Иван Немытченко, 7bits, Омск
PHP → Ruby on Rails →freelance →JazzCloud → Tulp → 7bits
2007 - Ruby on Rails
2007 - Ruby on Rails2008 - HAML/SASS
2007 - Ruby on Rails2008 - HAML/SASS2010 - Coffeescript
2007 - Ruby on Rails2008 - HAML/SASS2010 - Coffeescript2010 - Tequila → RABL
2007 - Ruby on Rails2008 - HAML/SASS2010 - Coffeescript2010 - Tequila → RABL2011 - Tulp2012 - MongoDB
2007 - Ruby on Rails2008 - HAML/SASS2010 - Coffeescript2010 - Tequila → RABL2012 - ActiveRecord vs Mongoid
MongoDB
MongoDB is a scalable, high-performance, open“   source NoSQL database                          ”
НЕТ ТРАНЗАКЦИЙ
НЕТ ТРАНЗАКЦИЙНЕТ ДЖОЙНОВ
Таблицы → Коллекции
Таблицы → КоллекцииСтроки → Документы
{ "_id" : ObjectId( "4fb8dd1324ec7c1344000003" ),  "agent" : "Ivan Nemytchenko",  "challenge" : "Introduce MongoDB documen...
{ "_id" : ObjectId( "4fb8dd1324ec7c1344000003" ),  "agent" : "Ivan Nemytchenko",  "missions": [    { "challenge" : "Introd...
Таблицы → КоллекцииСтроки → ДокументыИндексы → Индексы
MongoidObject Document Mapper
“   The philosophy of Mongoid is to provide a    familiar API to Ruby developers who have been    using Active Record or D...
Связи
has_many has_onebelongs_to
has_many       has_one      belongs_tohas_and_belongs_to_many
has_many                      has_one                     belongs_to               has_and_belongs_to_many        address:...
has_many       has_one      belongs_tohas_and_belongs_to_many   has_many :through
has_many       has_one      belongs_tohas_and_belongs_to_many   has_many :through
has_many       has_one      belongs_tohas_and_belongs_to_many   has_many :through     embeds_many      embeds_one     embe...
Lets Practice!
class Contact                              class Place  include Mongoid::Document                  include Mongoid::Docume...
{ "_id" : 1,  "name" : "Планета Суши"  "contacts" : [    { "_id" : 1,      "type" : "phone", "value" : "32-14-90" },    { ...
{ "_id" : 1,  "name" : "Планета Суши"  "contacts" : [    { "_id" : 1,      "_type" : "phone", "value" : "32-14-90" },    {...
class Contact                                  class Place  include Mongoid::Document                                    i...
Rating                   RatingType  embedded_in :place       embedded_in :categoryPlace                    Category  embe...
Place{ "_id" : 1,  "name" : "Планета Суши"  "ratings" : [    { "_id":1, "type":"Качество обслуживания", "value":4 },    { ...
Place{ "_id" : 1,  "name" : "Планета Суши"  "ratings" : [    { "_id":1, "type":"Качество обслуживания", "value":4 },    { ...
Place{ "_id" : 1,  "name" : "Планета Суши"  "ratings" : [    { "_id":1, "type":"Качество обслуживания", "value":4 },    { ...
Answer  embedded_in :questionQuestion                   Property  embedded_in :category      embedded_in :place  embeds_ma...
>> category.questions << Question.new(:value =>WiFi, :answers => [есть, нету])>> place.properties << Property.new(:questio...
Place{ "_id" : 1,  "name" : ".."  "contacts" : [    { "_type" : "phone", "value" : "32-14-90" },    { "_type" : "email", "...
Place            Review  Contacts        AuthorSummary  Ratings         Ratings  Properties      Comments  Categories →   ...
To embed or not to embed?      Соотношение запись/чтение        Жизненный цикл объекта   Так ли важна целостность данных?
Extra Stuff
GridFS     CarrierWave.configure do |config|       config.storage = :grid_fs       config.grid_fs_connection = Mongoid.dat...
Локализацияclass Person  include Mongoid::Document  field :first_name, :localize => true  field :last_name, :localize => t...
Полный фаршclass Person  include Mongoid::Document  include Mongoid::Timestamps  include Mongoid::Versioning  include Mong...
Гибридные приложенияclass TodoLog                        class Todo < ActiveRecord::Base  include Mongoid::Document       ...
Анти-mongoid    This tool exposes simplicity and power of“   MongoDB and leverages its differences                        ...
Спасибо. Давайте поговорим.         @inem       inem@bk.ru
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
ActiveRecord vs Mongoid
Upcoming SlideShare
Loading in …5
×

ActiveRecord vs Mongoid

6,424 views

Published on

DevConf 2012 ruby section.

Published in: Technology
0 Comments
9 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
6,424
On SlideShare
0
From Embeds
0
Number of Embeds
54
Actions
Shares
0
Downloads
41
Comments
0
Likes
9
Embeds 0
No embeds

No notes for slide

ActiveRecord vs Mongoid

  1. 1. ActiveRecord vs Mongoid Иван Немытченко, 7bits, Омск
  2. 2. PHP → Ruby on Rails →freelance →JazzCloud → Tulp → 7bits
  3. 3. 2007 - Ruby on Rails
  4. 4. 2007 - Ruby on Rails2008 - HAML/SASS
  5. 5. 2007 - Ruby on Rails2008 - HAML/SASS2010 - Coffeescript
  6. 6. 2007 - Ruby on Rails2008 - HAML/SASS2010 - Coffeescript2010 - Tequila → RABL
  7. 7. 2007 - Ruby on Rails2008 - HAML/SASS2010 - Coffeescript2010 - Tequila → RABL2011 - Tulp2012 - MongoDB
  8. 8. 2007 - Ruby on Rails2008 - HAML/SASS2010 - Coffeescript2010 - Tequila → RABL2012 - ActiveRecord vs Mongoid
  9. 9. MongoDB
  10. 10. MongoDB is a scalable, high-performance, open“ source NoSQL database ”
  11. 11. НЕТ ТРАНЗАКЦИЙ
  12. 12. НЕТ ТРАНЗАКЦИЙНЕТ ДЖОЙНОВ
  13. 13. Таблицы → Коллекции
  14. 14. Таблицы → КоллекцииСтроки → Документы
  15. 15. { "_id" : ObjectId( "4fb8dd1324ec7c1344000003" ), "agent" : "Ivan Nemytchenko", "challenge" : "Introduce MongoDB documents", "status" : "accepted" }
  16. 16. { "_id" : ObjectId( "4fb8dd1324ec7c1344000003" ), "agent" : "Ivan Nemytchenko", "missions": [ { "challenge" : "Introduce MongoDB documents", "status" : "done" }, { "challenge" : "Tell the truth about MongoDB", "status" : "considering" } ] }
  17. 17. Таблицы → КоллекцииСтроки → ДокументыИндексы → Индексы
  18. 18. MongoidObject Document Mapper
  19. 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 MongoDBs schemaless and performant document-based design, dynamic queries, and atomic modifier operations ” Durran Jordan, автор Mongoid
  20. 20. Связи
  21. 21. has_many has_onebelongs_to
  22. 22. has_many has_one belongs_tohas_and_belongs_to_many
  23. 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. 24. has_many has_one belongs_tohas_and_belongs_to_many has_many :through
  25. 25. has_many has_one belongs_tohas_and_belongs_to_many has_many :through
  26. 26. has_many has_one belongs_tohas_and_belongs_to_many has_many :through embeds_many embeds_one embedded_in
  27. 27. Lets Practice!
  28. 28. class Contact class Place include Mongoid::Document include Mongoid::Document field :type embeds_many :contacts field :value end embedded_in :placeendplace.contacts << Contact.new(:type => "phone", :value => "32-14-90")place.contacts << Contact.new(:type => "email", :value => "omskps1@rosinter.ru")place.save
  29. 29. { "_id" : 1, "name" : "Планета Суши" "contacts" : [ { "_id" : 1, "type" : "phone", "value" : "32-14-90" }, { "_id" : 2, "type" : "email", "value" : "omskps1@rosinter.ru" } ] }
  30. 30. { "_id" : 1, "name" : "Планета Суши" "contacts" : [ { "_id" : 1, "_type" : "phone", "value" : "32-14-90" }, { "_id" : 2, "_type" : "email", "value" : "omskps1@rosinter.ru" } ] }
  31. 31. class Contact class Place include Mongoid::Document include Mongoid::Document field :type embeds_many :contacts field :value end embedded_in :placeend class Email < Contact end class Phone < Contact endplace.contacts << Phone.new(:value => "32-14-90")place.contacts << Email.new(:value => "omskps1@rosinter.ru")place.save
  32. 32. Rating RatingType embedded_in :place embedded_in :categoryPlace Category embeds_many :ratings embeds_many :rating_types
  33. 33. Place{ "_id" : 1, "name" : "Планета Суши" "ratings" : [ { "_id":1, "type":"Качество обслуживания", "value":4 }, { "_id":2, "type":"Чистота", "value":5 } ] }Rating RatingType embedded_in :place embedded_in :categoryPlace Category embeds_many :ratings embeds_many :rating_types
  34. 34. 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 :categoryPlace Category embeds_many :ratings embeds_many :rating_types
  35. 35. 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)
  36. 36. Answer embedded_in :questionQuestion Property embedded_in :category embedded_in :place embeds_many :answers field :question field :answerCategory Place embeds_many :questions embeds_many :properties
  37. 37. >> category.questions << Question.new(:value =>WiFi, :answers => [есть, нету])>> place.properties << Property.new(:question =>WiFi, :answer => есть)
  38. 38. 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" : ".." }]}
  39. 39. Place Review Contacts AuthorSummary Ratings Ratings Properties Comments Categories → User Category Reviews → RatingTypes Questions Answers
  40. 40. To embed or not to embed? Соотношение запись/чтение Жизненный цикл объекта Так ли важна целостность данных?
  41. 41. Extra Stuff
  42. 42. 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 endgem carrierwave-mongoid, :require => carrierwave/mongoid
  43. 43. Локализацияclass Person include Mongoid::Document field :first_name, :localize => true field :last_name, :localize => trueend{ "_id" : 1, "first_name" : { "ru" : "Иван" }, "last_name" : { "ru" : "Немытченко" } }
  44. 44. Полный фаршclass Person include Mongoid::Document include Mongoid::Timestamps include Mongoid::Versioning include Mongoid::Paranoia field :first_name field :last_name key :first_name, :last_nameend
  45. 45. Гибридные приложения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 privateend def create_log TodoLog.create( :title => title, :done => !!done, :todo_id => id ) end end https://github.com/a2ikm/activerecord-and-mongoid-sample
  46. 46. Анти-mongoid This tool exposes simplicity and power of“ MongoDB and leverages its differences ” Алексей Петрушин, автор MongoModelhttp://alexeypetrushin.github.com/mongodb_model/index.html
  47. 47. Спасибо. Давайте поговорим. @inem inem@bk.ru

×