I asked a similar question a couple of days ago, but I realized that I didn't ask it quite right.
In a Rails app with Manager and Employee models, let's say that all managers are employees, but not all employees are managers. I needed a solution for a user to be able to act as a manager and employee, both having different attributes and methods.
I was told to use Single Table Inheritance, which is very useful, but that gave the user the properties of both at the same time. What I would like is for the user (not every user) to be able to act as a manager and employee, but not both at the same time.
So, some users can either be a manager or employee, but not both. Some users can only be an employee.
Any ideas on what relationship I should use for this?
You could use STI like so:
create_table :users do |t|
t.string :name
t.string :type # index this
end
class User < ActiveRecord::Base
# attributes -- name, type
def to_s
"#{name} (Generic User)"
end
end
class Manager < User
def to_s
"#{name} (Manager)"
end
end
class Employee < User
def to_s
"#{name} (Employee)"
end
end
puts User.new(name: "Mr User")
# => "Mr User (Generic User)"
puts Manager.new(name: "Mr Manager")
# => "Mr Manager (Manager)"
puts Employee.new(name: "Mr Employee")
# => "Mr Employee (Employee)"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.