0

我有2个模型,例如任务模型和任务相关模型 任务有许多父任务和子任务。Rails 3:与多态关联的多对多关系

已新增下列协会 -

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表中,relation_type为'Task',但我想存储relati on_type作为父任务的“父”和子任务的“子”。

任何人都可以请帮我在这。

+1

这个模型看起来不必要的复杂 - 你能澄清(用文字,而不是代码)一个任务需要与什么关联吗? – PinnyM

+0

想要将任务模型与任务关联起来作为父任务和子任务。需要将此关联存储在task_relation模型中,哪个任务是父任务,哪个任务是子任务。 –

+0

预计每个任务会有多个父母和孩子吗? – PinnyM

回答

0

首先,删除relation多态关联 - 它不是必需的。现在,修改你的Task模型是这样的:

# This association relates to tasks that are parents of self 
has_many :parent_task_relations, class_name: 'TaskRelation', foreign_key: 'child_task_id' 
# And this association relates to tasks that are children of self 
has_many :child_task_relations, class_name: 'TaskRelation', foreign_key: 'parent_task_id' 

has_many :child_tasks, :through => :child_task_relations 
has_many :parent_tasks, :through => :parent_task_relations 

而且你应该做的事。

为了说明这可能是使用 - 说你有一个任务a和需要来分配任务B作为父母,和任务C作为一个孩子。你可以做到这一点,像这样:

a.parent_tasks << b 
a.child_tasks << c 

这会对你的数据库的代码上同样的效果:

a.parent_task_relations.create(parent_task: b) 
a.child_task_relations.create(child_task: c) 

这是相同的(到数据库)为:

TaskRelation.create(parent_task: b, child_task: a) 
TaskRelation.create(parent_task: a, child_task: c) 
+0

我早些时候已经添加了这个关系......但根据它在应用程序中的使用,我需要修改父任务与子任务之间的不同以及原始任务。 –

+0

For.eg.如果有3个任务A,B和C,并且我将B作为父任务与A和C作为子任务关联到A.并且可以有很多。所以为了区分谁是父母和谁是孩子。我需要这种多态关联。 –

+0

不,你不知道。在你给的例子中,你可以简单地创建2个TaskRelations,一个带有“parent:B,child:A”,另一个带有“parent:A,child:C”。在第一个关系中,A将被检测为孩子,而第二个A将被检测为父母。 – PinnyM