0

I need the "nps" field value from the latest Feedback record for each account based on the created_at date which is a datetime field. I have worked on this, but it's pulling back the first record for each account. Am I going obviously wrong somewhere?

nps_total = 0
nps_records = Feedback.select([:nps, 'MAX(created_at)']).group(:account_id).each do |record| 
  nps_total += record.nps
end
Gareth Burrows
  • 1,142
  • 10
  • 22

1 Answers1

0

Well, from what I understood, you have 2 models : Account and Feedback and Account has_many :feedbacks. Now, your Feedback model has a "nps" value.

If I'm right, you just have to do something like

nps_total = 0
Account.all.each do |account|
 nps_total += account.feebacks.order("created_at").last.nps
end
Er...
  • 526
  • 4
  • 10
  • This would *almost* work, except I don't think the association maintains order by `create_at`. However, with an appropriate `scope` added to `Feedback`, this could work. – lurker Sep 17 '14 at 19:04
  • Seeing [this](http://stackoverflow.com/questions/4870531/find-the-newest-record-in-rails-3), I think you're right, I'm gonna update my answer :) – Er... Sep 18 '14 at 07:17