Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4ruby-on-rails-5

how to access class method from instance method


I have model:

class UserWeight < ActiveRecord::Base

  self.table_name = 'Weight'

  scope :logged_between, lambda { |start_date, end_date|
    where(weight_date: start_date.to_date...(end_date.to_date.end_of_day)) unless
    start_date.nil? || end_date.nil?
  }

  # returns the sum of points 
  def total_points
      self.class.Userweight
    (UserWeight.blank?) ? 0 : UserWeight.inject(0) {|a, e| a + e.points}
  end
end

Controller:

@weights = weight_usages.logged_between(params[:start_date], end_date)

I get following data in weights:

weights: [
{
weight: "170.0",
weight_date: "2016-12-28",
points: 1
},
{
weight: "185.0",
weight_date: "2017-01-04",
points: 1
}
.......
 ]

Active record is returning collection of arrays. I want to access class method and do the sum in the instance method. based on the data i want to return total points 2 from instance method. Any idea how can i do that?

Thanks


Solution

  • The method looks to make little to no sense, because total_points is an instance method, so why would you want to present the all records points's sum in an instance method?

    Beside the above note, use ActiveRecord's methods. You are looking for sum:

    UserWeight.sum(:points)
    

    In method:

    self.class.sum(:points)