简体   繁体   English

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

[英]Rails: How do I validate model based on parent's attributes?

I have three models named Metric, Entry, and Measurement: 我有三个名为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

They are associated, and I can create nested instances of each this way: 它们是关联的,我可以这样创建每种的嵌套实例:

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})

How do I validate the measurements for blood pressure based on the :required_measurement_names attribute in the Metric model? 如何基于Metric模型中的:required_measurement_names属性验证血压测量值? For example, how would I ensure that only "Systolic" and "Diastolic" are entered as measurements? 例如,如何确保仅输入“收缩压”和“舒张压”作为测量值?

Is there a better way to about setting up these associations and validations? 是否有更好的方法来设置这些关联和验证?

Thanks! 谢谢!

Looks like entry is a join model between Measurement and Metric. 入口似乎是Measurement和Metric之间的联接模型。 so it makes sense for your validation to go there. 因此进行验证很有意义。

To ensure that all metrics required metrics are covered 为了确保涵盖所有必需指标

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

To ensure that only accepted metrics are included (assuming optional metrics are accepted too). 为了确保仅包含接受的指标(假设也接受了可选指标)。

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

Putting it all together add the above and following to the Entry model 放在一起将以上和以下内容添加到Entry模型中

validate: validate_accepted_measurements, :validate_required_measurements

NB my Ruby is a little rusty so this isn't guaranteed to work after copying and pasting, but it should get you close enough to fix the syntax errors that slipped through. 注意:我的Ruby有点生锈,因此不能保证在复制和粘贴后都能正常工作,但是它应该使您足够接近以解决漏掉的语法错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM