I have three models named Metric, Entry, and 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? 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. so it makes sense for your validation to go there.
To ensure that all metrics required metrics are covered
To ensure that only accepted metrics are included (assuming optional metrics are accepted too).
Putting it all together add the above and following to the Entry model
N.B. 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.