【发布时间】:2013-12-13 11:43:02
【问题描述】:
我有 2 个模型,例如任务模型和任务关系模型 Task 有很多父任务和子任务。
已添加以下关联 -
Task.rb
has_many :from_tasks, :as => :relation, :class_name => "TaskRelation",
:foreign_key => "task_from_id", :source => :parent,
:conditions => {:relation_type => 'Parent'}, :dependent => :destroy
has_many :to_tasks , :as => :relation, :class_name => "TaskRelation",
:foreign_key => "task_to_id", :source => :child,
:conditions => {:relation_type => 'Child'}, :dependent => :destroy
has_many :child_tasks, :through => :from_tasks, :dependent => :destroy
has_many :parent_tasks, :through => :to_tasks, :dependent => :destroy
accepts_nested_attributes_for :to_tasks, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :from_tasks, :reject_if => :all_blank, :allow_destroy => true
TaskRelation.rb
belongs_to :parent_task, :class_name => "Task", :foreign_key => "task_from_id"
belongs_to :child_task, :class_name => "Task", :foreign_key => "task_to_id"
belongs_to :relation, :polymorphic => true
当我保存任务表单时,它还会将 parent_tasks 和子任务保存在 task_relations 表中,其中关系类型为“任务”,但我想将关系类型存储为父任务的“父”和子任务的“子”。
谁能帮帮我。
【问题讨论】:
-
这个模型看起来不必要的复杂——你能准确地(用文字而不是代码)阐明一个任务需要与什么相关联吗?
-
想将任务模型与任务关联为父任务和子任务。需要将此关联存储在task_relation模型中,哪个任务是父任务,哪个是子任务。
-
每个任务是否预计会有不止一个父母和孩子?
-
是...任务可以有多个父任务和多个子任务
标签: ruby-on-rails ruby many-to-many has-many-through polymorphic-associations