Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mongoid example generating possibly excessive db queries
# 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