Rails模拟约束和子约束

时间:2014-08-27 08:49:47

标签: ruby-on-rails-4 mongoid constraints multiple-inheritance matching

我正在构建一个包含当前项目任务的调度平台

假设项目存在一些全局约束(金钱,人员等),并且每个任务也有单独的约束。

最重要的是我必须将每个全局约束与每个同一项目任务的约束相匹配

现在最重要的是,除了具有自然(金融 - >浮动,人 - >整数)之外,约束也可以有一种类型(例如:工资成本,原材料成本等) 。)

做轨道的方法是什么?

我想到了类似的东西,但看起来(?)有点过于重复:

class Constraint
    field :type, type: String
    belongs_to :task
    belongs_to :global_constraint
end

class Constraint::Financial < Constraint
    field :cost, type: Float
end

class Constraint::People < Constraint
    field :number, type: Integer
end
...

现在的问题是我需要一个类似的GlobalConstraint结构

class GlobalConstraint
    field :type
    belongs_to :project
    has_many :constraints, polymorphic: true
end

class GlobalConstraint::Financial < Constraint
    field :cost, type: Integer
end

对于匹配算法,我想做类似的事情

(inside the Constraint class)

def find_global_constraint
        self.global_constraint = self.task.project.global_constraints.find_by(:type => self.type)
end

(inside GlobalConstraint::xxx class) :

def check_integrity
    "Requires custom implementation !"
end

示例:

GlobalConstraint::Financial
def check_integrity
    sum = Float.new
    self.sonstraints.each do |constraint|
        sum += constraint.cost
    end
    sum < cost
end

GlobalConstraint::People
def check_integrity
    sum = Integer.new
    self.sonstraints.each do |constraint|
        sum += constraint.cost
    end
    sum < number
end

0 个答案:

没有答案