Search code examples
sqlruby-on-railsdatabasetimelinemultiple-tables

What is the best approach to save multiple temperature-curves (which are measured at the same time) in a Database using Rails and SQL


what is the best approach to save multiple temperature-curves by using Ruby On Rails and a SQL-database. The temperature curves are are measured at the same time. And the time for each measured value musst be stored in seconds.

This picute show my problem in an UML. But the assoziation between timeline and curve-measurment isn't correct. Each timeline-value can have several curve-measurments but not in the same curve. In the same curve alle timeline-values must be unique.

Pic 1

In this solution all timeline-values can have several curve-measurments. This ist correct but in this picutre a timeline-value can have several curve-mesaurments in the same curve and that is wrong.

Pic 2

I hope you understand my problem and you can give me some hint to a better approach.


Solution

  • It looks like your CurveMeasurement should be a join between Curve and Timeline:

    class Curve < ActiveRecord::Base
      has_many :curve_measurements
      ...
    end
    
    class Timeline < ActiveRecord::Base
      has_many :curve_measurements
      ...
    end
    
    class CurveMeasurement < ActiveRecord::Base
      belongs_to :curve
      belongs_to :timeline
    
      validates :curve_id, uniqueness: { scope: :timeline_id }
      validates :timeline_id, uniqueness: { scope: :curve_id }
      ...
    end
    

    The important parts for your requirements are the uniqueness scopes in the CurveMeasurement model - this ensures that you can't have more than one measurement for a given curve at a given timeline point.


    It would also be possible to do this without the timeline value being a separate model:

    class Curve < ActiveRecord::Base
      has_many :curve_measurements
      ...
    end
    
    class CurveMeasurement < ActiveRecord::Base
      belongs_to :curve
    
      validates :timeline_value, uniqueness: { scope: :curve_id }
      ...
    end
    

    If you wanted to enforce a discrete set of timeline_values, you can use further validations: either numericality or inclusion (see http://guides.rubyonrails.org/active_record_validations.html )