Rails:如何根据父级属性验证模型?

时间:2011-04-08 07:32:44

标签: ruby-on-rails ruby validation associations

我有三个名为Metric,Entry和Measurement的模型:

class Metric < ActiveRecord::Base
  has_many :entries
  attr_accessible :name, :required_measurements, :optional_measurements
end

class Entry < ActiveRecord::Base
  belongs_to :metric
  has_many :measurements
  attr_accessible :metric_id
end

class Measurement < ActiveRecord::Base
  belongs_to :entry
  attr_accessible :name, :value
end

它们是关联的,我可以用这种方式创建嵌套实例:

bp = Metric.create(:name => "Blood Pressure", :required_measurement_names => ["Diastolic", "Systolic"])

bp_entry = bp.entries.create()

bp_entry.measurements.create({:name => "Systolic", :value =>140}, {:name => "Diastolic", :value =>90})

如何根据度量标准模型中的:required_measurement_names属性验证血压测量值?例如,我如何确保仅输入“收缩压”和“舒张压”作为测量值?

有没有更好的方法来设置这些关联和验证?

谢谢!

1 个答案:

答案 0 :(得分:1)

看起来条目是Measurement和Metric之间的连接模型。所以你的验证去那里是有意义的。

确保涵盖所有指标所需的指标

def validate_required_measurements
  metric.required_measurements.each{ |requirement| 
     unless (measurements.map{|measurement| measurement.name}.includes requirement)
       errors.add_to_base "required measurement #{requirement} is missing"  
     end
  }
end

确保仅包含已接受的指标(假设也接受可选指标)。

def validate_accepted_measurements
  measurements.each{ |measurement| 
     unless ((metric.required_measurements + metric.optional_measurements).include measurement.name )
       errors.add_to_base "invalid measurement #{measurement.name} for metric"  
     end
  }
end

将所有内容添加到条目模型

中添加以上内容
validate: validate_accepted_measurements, :validate_required_measurements

N.B。我的Ruby有点生疏,所以这不能保证在复制和粘贴后工作,但它应该让你足够接近以修复滑过的语法错误。