从ActiveRecord引用两个级别的祖先

时间:2014-10-07 18:37:29

标签: ruby-on-rails activerecord ruby-on-rails-4

想象一个类似于GitHub或GitLab问题的模型。有三个实体:

Project --- Milestones --- Issues

但是,由于问题可能还没有关联的里程碑,因此问题也会引用项目实体。在代码中:

class Project < ActiveRecord::Base
  has_many :issues
  has_many :milestones

end

class Milestone < ActiveRecord::Base
  belongs_to :project
  has_many :issues

end

class Issue < ActiveRecord::Base
  belongs_to :project
  belongs_to :milestone

end

有没有办法告诉Rails在任何给定的问题中,以下内容必须保留self.milestone.project == self.project

此外,有没有办法让以下工作正常? project.milestones.first.issues.new()并且新创建的问题是否正确填充了project引用?

1 个答案:

答案 0 :(得分:0)

我不会在问题模型中添加项目关联。而是将has_many :issues, :through => :milestones关联添加到Project模型。在delegates模型上添加Issue指令,以便您可以直接从问题中访问项目。

class Project < ActiveRecord::Base
  has_many :milestones
  has_many :issues, :through => :milestones
end

class Milestone < ActiveRecord::Base
  belongs_to :project
  has_many :issues
end

class Issue < ActiveRecord::Base
  belongs_to :milestone
  delegates :project, :to => :milestone
end

鉴于产品,找到所有问题:

project = Project.find(1)
project.issues

鉴于里程碑,找到所有问题:

milestone = Milestone.find(1)
milestone.issues

考虑到问题,请联系它的项目:

issue = Issue.find(1)
issue.project