Search code examples
ruby-on-railsruby-on-rails-3mathrecords

Rails: Count specific records then do calculation


I am attempting to do a rails record count then do a calculation from those records to give me a final number:

Example

100 Records = A
30 Records = B
Total Records = C

A+(-B)=C

I am not even going to show you what I tried... in retrospect I am very new to rails and it made no logical sense!

UPDATE: To further expand:

When implementing this I realized that there might be some slight difference from what it solves above. I have a MVC called "POST" It was some records within the table one specifically is called "VOTE" the vote integer will consist of 1 or (-1). Each post will have a VOTE column that represent a value of 1 or (-1). I am trying to create an analytic metric that consists of the following:

TOTAL = (Total posts with Value 1) + (Total posts with Value -1) Example

1234 = 2000 + (-776)

Thank you in advance!


Solution

  • In general, C = A.count + B.count

    If you want C to be the union of A and B, then do

    C = A & B
    C.count # Number of elements in C
    

    For your specific case:

    yes_votes = POST.where('VOTE = ?', 1)
    no_votes = POST.where('VOTE = ?', -1)
    total = yes_votes.count - no_votes.count