0

假设我有一个 Person 和一个 Task 表。一个人可以有许多任务,但有时,一个人可以有一个主要任务,它是其他任务的组合。因此,为此我插入了多行分组的任务。但我不想添加任何其他表,如 BigTask。

那么有没有办法通过代理来处理创建任务,比如

Person 通过 Proxy(abstract) 与 Task 相关联。

这样我就可以保存并初始化一个代理,这会给我一个包含 0 个或更多任务对象的数组。

4

1 回答 1

0

Fleshing out the ideas expressed in the comments above, I believe something like this should work:

class Task < ActiveRecord::Base
  belongs_to :person
  belongs_to :big_task, class_name: "Task"
  has_many :sub_tasks, class_name: "Task", foreign_key: "big_task_id"
end

class Person < ActiveRecord::Base
  has_many :big_tasks, class_name: "Task"
  has_many :tasks
  has_many :sub_tasks, through: tasks
end

Then, of course, you will need to define a "big_task_id" field on your Task model so that you can associate it with the "big task."

This should enable things like:

p = Person.find(id)
biggie = p.tasks.create(title: "Clean house")
biggie.tasks.create(title: "Vaccuum")
biggie.tasks.create(title: "Wash Windows")
p.tasks.count # 3
p.sub_tasks.count # 2
p.big_tasks.count # 1
于 2013-11-05T20:22:32.893 回答