在mongoid中的关联

时间:2013-01-28 04:57:49

标签: ruby-on-rails ruby-on-rails-3 associations mongoid

我有三个模型,员工,工作,休假。如下所示:

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。这怎么可能。提前谢谢。

2 个答案:

答案 0 :(得分:0)

我对Mongoid并不熟悉。您可以阅读更多有关mongoid中关系的here

这是一个非常简单的例子。希望它会有所帮助。

这是模型定义:

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]

答案 1 :(得分:0)

我认为你需要在LeaveDay中添加'belongs_to:employee',在Employee中添加'has_many:leave_days'。所以,@ emp.leave_days将获得特定员工所有工作的所有休假。同样,@ emp.job.leave_days将返回cuttent员工当前工作的leave_days。