Oracle 11g XEのHRスキーマのテーブルをActiveRecordで書いてみる

Oracle 11g XEのHRスキーマのテーブルをActiveRecordで書いてみる

ER図はこちら: 表と表クラスタ

class Region < ActiveRecord::Base
  primary_key = :region_id
  has_many :countries
end

class Country < ActiveRecord::Base
  primary_key = :country_id
  belongs_to :region
  has_many :locations
end

class Location < ActiveRecord::Base
  primary_key = :location_id
  belongs_to :country
  has_many :departments
end

class Department < ActiveRecord::Base
  primary_key = :department_id
  belongs_to :location
  has_many :employees
  has_many :job_histories

  def manager
    Employee.where(employee_id: manager_id)
  end
end

class Employee < ActiveRecord::Base
  primary_key = :employee_id
  belongs_to :job
  belongs_to :department
  has_many :job_histories

  def manager
    Employee.where(employee_id: manager_id)
  end
  def members
    Employee.where(manager_id: employee_id)
  end
end

class JobHistory < ActiveRecord::Base
  self.table_name = :job_history
  #composite primary key
  belongs_to :employee
  belongs_to :job
  belongs_to :department
end

class Job < ActiveRecord::Base
  primary_key = :job_id
  has_many :job_histories
  has_many :employees
end

p Region.count
p Country.count
p Location.count
p Department.count
p Employee.count
p JobHistory.count
p Job.count

p '#####################Departments#####################'
Department.all.each do |dept|
  p '***************************************'
  p dept.inspect
  p dept.location.inspect
  p dept.employees.inspect
  p dept.job_histories.inspect
  p dept.manager.inspect
end

p '#####################Employees#####################'
Employee.all.each do |emp|
  p '***************************************'
  p emp.inspect
  p emp.job.inspect
  p emp.department.inspect
  p emp.job_histories.inspect
  p emp.manager.inspect
  p emp.members.inspect
end

動いてはいる。あとはsequence_nameを書き足したらそれなりなのかな。

13.6.17追記:シーケンスオブジェクトはこの3つしかないから何もしなくてOKだった。。

  • LOCATIONS_SEQ
  • EMPLOYEES_SEQ
  • DEPARTMENTS_SEQ

追記終わり。

テーブル名を上書きするのにtable_name = :job_historyではだめなのね。selfを付けないと。主キーを上書きしているところはself付けていないけどいいのかな。。

20130622追記:よくないようです。

managerを巡るあれやこれやはアソシエーションやscopeでうまくやれないのかな。dept.managerとかme.managerとかboss.membersとか書きたかったんだけどね。。ああ、書けないってことは書かない方がいいってことなのかな。