Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## all_diff will calculate some cumulative fields and save them back to the db
- ## Model
- class Reading < ActiveRecord::Base
- def self.all_diff(unit_id)
- first = find(:first, :conditions => ["unit_id = ?", unit_id], :order => "date asc" )
- counter_last = first.counter
- date_last = first.date
- find(:all, :conditions => ["unit_id = ?", unit_id], :order => "date asc" ).each do |r|
- r.diff_days = r.date - date_last
- # analog meters will reset to 0000 when after reaching 9999. Difficult to recognise automatically, but will try
- if r.counter < counter_last and r.counter < 9000 and counter_last >9000:
- r.diff_counter = r.counter+ 10000- counter_last
- elsif
- r.diff_counter = r.counter - counter_last
- end
- if r.type == "ElectricityReading"
- co2_factor = 0.43
- elsif r.type == "GasReading"
- co2_factor = 2.28
- elsif r.type == "WaterReading"
- co2_factor = 5
- else
- co2_factor = nil
- end
- r.diff_co2 = r.diff_counter.to_f * co2_factor
- #if this is the first record, the denominator will be zero, so we'll skip it
- unless r.diff_days == 0
- r.diff_counter_days = r.diff_counter.to_f / r.diff_days.to_f
- r.diff_co2_days = r.diff_counter_days * co2_factor
- end
- logger.debug r.type
- r.save
- counter_last = r.counter
- date_last =r.date
- end
- end
- ## Sub Class
- class ElectricityReading < Reading
- ## Controller
- def create_electricity_reading
- @reading = ElectricityReading.new(params[:reading])
- respond_to do |format|
- if @reading.save
- flash[:notice] = "created E-reading ok"
- format.html { redirect_to :action =>"index" }
- else
- format.html { render :action => "new" }
- end
- end
- ElectricityReading.all_diff(params[:reading][:unit_id])
- end
Add Comment
Please, Sign In to add comment