Created
February 16, 2012 21:58
-
-
Save eimermusic/1848171 to your computer and use it in GitHub Desktop.
Mongoid example generating possibly excessive db queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Monogid Models | |
class Employee | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
field :ssid, type: String | |
field :name, type: String | |
index :name | |
belongs_to :department, index: true | |
belongs_to :company, index: true | |
validates :ssid, uniqueness: true | |
end | |
class Department | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
field :name, type: String | |
field :employee_count, type: Integer | |
index :name | |
has_many :employees, dependent: :destroy | |
belongs_to :company, index: true | |
end | |
class Company | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
field :name, type: String | |
field :employee_count, type: Integer | |
index :name | |
has_many :departments, dependent: :destroy | |
has_many :employees, dependent: :destroy | |
end | |
# Code to run in console or wherever. | |
# Note: the real-world case all data comes from a data file containing all the data used to generate the association "tree". Imagine a csv with each row containing an employee and the names of their department and company. Also imaging some more updates being done when an existing dept or corp is found. | |
employee = Employee.new(ssid:"123", name:"Person One") | |
department = Department.first(:conditions => { :name => "Sales" }) | |
if department.nil? | |
department = Department.new | |
department.name = "Sales" | |
else | |
employee.company = department.company | |
end | |
employee.department = department | |
company = Company.first(:conditions => { :name => "Apple" }) | |
if company.nil? | |
company = Company.new | |
company.name = "Apple" | |
end | |
employee.department.company = company if employee.department.company.nil? | |
employee.company = company | |
employee.department.save | |
employee.department.inc(:employee_count, 1) | |
employee.department.company.save | |
employee.department.company.inc(:employee_count, 1) | |
employee.save |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment