轨模拟约束和子约束(Rails simulating Constraints and sub-Con

2019-10-20 19:08发布

我建立一个调度平台,任务当前项目

比方说,有该项目的一些全局约束(资金,人员等),并且每个任务也有个别约束。

大不了就是,我要每个全局约束相匹配的同一个项目的任务每个约束

现在,真正的大问题,是除了具有自然(金融 - >浮动,人 - >整数)的限制也可以有一个类型(例如:工资成本,原材料成本等)

什么是轨道办法做到这一点?

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

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
文章来源: Rails simulating Constraints and sub-Constraints