我有三个模型,员工,工作,休假日。
class Employee
field :name
belongs_to :job
end
class Job
field :job_title
has_many :employees
has_many :leave_days
end
class LeaveDay
belongs_to :job
field :no_of_leave_days
end
我想建立一种关系,在其中我想要跟踪与其工作相关的员工no_of_leave_days
。怎么可能。提前谢谢。
我认为您需要在休假日中添加"belongs_to:员工",在员工中添加"has_many:leave_days"。 因此,@emp.Leave_Days将为您提供特定员工所有工作的所有假期。 同样,@emp.job.leave_days 将返回 cuttent 员工当前作业的leave_days。
我对Mongoid不太熟悉。你可以在这里阅读更多关于mongoid关系的信息。
这是一个非常简单的例子。希望它能有所帮助。
这是模型定义:
class Employee
include Mongoid::Document
field :name
belongs_to :job
end
class Job
include Mongoid::Document
field :job_title
has_many :employees
embeds_many :leave_days
end
class LeaveDay
include Mongoid::Document
embedded_in :job
field :no_of_leave_days
end
和使用示例:
pry(main)> j = Job.create(job_title: "Test Job")
=> #<Job _id: 510633e0784931179a000001, _type: nil, job_title: "Test Job">
pry(main)> LeaveDay.create(job: j, no_of_leave_days: 1)
=> #<LeaveDay _id: 5106348f784931179a000002, _type: nil, no_of_leave_days: 1>
pry(main)> LeaveDay.create(job: j, no_of_leave_days: 2)
=> #<LeaveDay _id: 51063687784931179a000003, _type: nil, no_of_leave_days: 2>
pry(main)> LeaveDay.create(job: j, no_of_leave_days: 3)
=> #<LeaveDay _id: 51063689784931179a000004, _type: nil, no_of_leave_days: 3>
pry(main)> Job.first.leave_days.map(&:no_of_leave_days)
=> [1, 2, 3]
pry(main)> Employee.create(name: 'Employee name', job: Job.first)
=> #<Employee _id: 510637cf784931179a000005, _type: nil, name: "Employee name", job_id: "510633e0784931179a000001">
pry(main)> Employee.first.job.leave_days.map(&:no_of_leave_days)
=> [1, 2, 3]