Skip to content

ActiveRecord integration

Vladimir Dementyev edited this page May 27, 2015 · 3 revisions

You can associate you metrics with ActiveRecord model using has_metrics method.

class Account < ActiveRecord:Base
  # without any arguments it generate instance method 'metrics', 
  # which return AccountMetrics instance with attribute account_id set to instance id
  has_metrics
end

Account.find(1).metrics.write #=> writes point (account_id: 1) to specified (in AccountMetrics) series
Account.find(1).metrics.time(:hour) #=> select * from ... where account_id=1 group by time(1h)

There are several options for has_metrics:

  • foreign_key (default to Rails's model foreign_key);
  • class_name - name of metrics class as string;
  • inherits - array of owner instance attributes to be added to metrics point by default.
# suppose we have user which belongs to account
# and our metrics contain information about both
class User < ActiveRecord::Base
  belongs_to :account
  has_metrics inherits: [:account_id]
end

u=User.find(10)
#<User: id=10, account_id=1>
u.metrics.write # writes point (user_id: 10, account_id: 1)
Clone this wiki locally