0

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Andrey for your response. I am just trying to understand the concept. I edited question for the data i am getting in array. when i do self.class.sum(:points) in method i am getting much bigger number. based on data i should get 2.
@User4432432432 to see what you have in records, do UserWeight.pluck(:points) - this will produce an array of points
when i do that i get [nil, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, nil, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1] and it does add to 23 but on application it shows me 2 Weights arrays with points = 1 and 4 with 0. so did not understand why its returning 23.
@User4432432432 in application (in controller) you are filtering it by means of scope logged_between. THUS: call the sum(:points) on weight_usages.logged_between(params[:start_date], end_date): weight_usages.logged_between(params[:start_date], end_date).sum(:points)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.