This document discusses database modeling for a system with companies, departments, and employees. It describes setting up composite primary keys to link the three tables together and using associations and joins to efficiently query across the tables. Methods are defined on the Company model to count employees. A view is created to select large companies with over 1000 employees.
33. Department
class Department < ActiveRecord::Base
set_primary_keys :company_id,
:department_id
has_many :employees,
:foreign_keys =>
[:company_id,
:department_id]
34. Company
class Company < ActiveRecord::Base
def employees_size
Employee.count(
:conditions =>
['company_id = ?', id])
end
38. CREATE VIEW big_campanies AS
SELECT * FROM companies WHERE id IN
(SELECT company_id FROM
(SELECT compay_id, count(id) AS c
FROM employees
GROUP BY company_id) AS t
WEHRE c > 1000)