Use has_one or belongs_to

There are two models: Companies and Employees
table companies
  integer :ceo_id
  integer :cfo_id
end
table employees
  string :name
end
How should I implement <company instance>.ceo and <company instance>.cfo
which will return the CEO's and CFO's employee records?
Should I do:

There are two models: Companies and Employees

table companies

integer :ceo_id

integer :cfo_id

end

table employees

string :name

end

How should I implement .ceo and .cfo

which will return the CEO’s and CFO’s employee records?

Should I do:


(1)

class Company

belongs_to :ceo, :class_name => ‘Employee’

belongs_to :cfo, :class_name => ‘Employee’

end

or

(2)

class Company

has_one :ceo, :class_name => ‘Employee’, :primary_key => :ceo_id,

:foreign_key => :id

has_one :cfo, :class_name => ‘Employee’, :primary_key => :cfo_id,

:foreign_key => :id

end


(1) is definitely simpler, but I don’t quite get over the psychological

hurdle why Company should ‘belongs_to’ a ceo employee, but not ‘has_one’

ceo. Am I missing something?

You might have a good reason, but what about just add a :title attribute to Employees. Then you just ask for Company.include(“employees”).where(“employee.title=‘ceo’”)? (my query might not be exact but you get the idea…)

Worst case you can add logic to your models to validate to only allow one ceo / cfo per company.

Just a thought.

yeah…David is right.
Just add a boolean field for each of the attributes i.e ceo and cfo in the employees because if you look at the picture in real world, an employee could be either an ceo, an cfo or just an employee.

There are two models: Companies and Employees
table companies
integer :ceo_id
integer :cfo_id
end
table employees
string :name
end
How should I implement <company instance>.ceo and <company instance>.cfo
which will return the CEO's and CFO's employee records?
Should I do:
------
(1)
class Company
belongs_to :ceo, :class_name => 'Employee'
belongs_to :cfo, :class_name => 'Employee'
end
or
(2)
class Company
has_one :ceo, :class_name => 'Employee', :primary_key => :ceo_id,
:foreign_key => :id
has_one :cfo, :class_name => 'Employee', :primary_key => :cfo_id,
:foreign_key => :id
end

The second one will not work with the db schema you have shown, the id
fields would have to be in the Employee.

I would suggest maybe company has_many employees and employee
belongs_to company and then use roles to specify their function.
Google for Rails Roles and you will find many examples on how to do
this. The simplest is just a role field in the employee record, but
if you want an employee to be able to fill multiple roles then you
probably need a Roles table.

-----
(1) is definitely simpler, but I don't quite get over the psychological
hurdle why Company should 'belongs_to' a ceo employee, but not 'has_one'
ceo. Am I missing something?

No, you are not missing anything, sometimes the words just do not seem
to match the real world.

Colin

David Kahn-3 wrote: