Reputation: 37
I would like to get statistics for every company. Is dividing every month and totaling possible? On the other hand, is a function required?
ResultModel
company_id , count , date
1,3,2014-01-06 06:14:03 +0000
1,3,2014-01-08 16:14:03 +0000
1,3,2014-02-06 07:05:03 +0000
1,3,2014-03-06 36:14:04 +0000
1,3,2014-03-06 26:12:05 +0000
1,3,2014-03-06 06:23:05 +0000
2,3,2014-03-06 06:23:05 +0000
Result
company_id , month , total
1 , 201401 , 2
1 , 201402 , 1
1 , 201403 , 3
Upvotes: 0
Views: 29
Reputation: 76774
Alias Column
One way you could achieve this would be by using an alias
column, as described in this Railscast (06:30):
You could do something like this:
#app/models/result.rb
Class Result < ActiveRecord::Base
has_many :more_results, -> { select("#{Result.table_name}.*, #{ResultModel.table_name}.month AS new_month")}
end
This will give you the ability to pull the associative data from your database, allowing you to perform calculations on it. I believe this will cause an n+1
query issue, but hopefully will give you something to work from.
-
An alias is a feature of SQL that is supported by most, if not all, relational database management systems (RDBMSs). Aliases provide database administrators, as well as other database users, with the ability to reduce the amount of code required for a query, and to make queries generally simpler to understand. In addition, aliasing can be used as an obfuscation technique to protect the real names of database fields.
The problem you have is calling your single model's data will not give you access to all the data you require to get it working. Instead, you should certainly look at how you're able to call other model's data with a single association
Count
I'm not sure what you mean by wanting to "count the number of months", but I know you can include a COUNT
method like this:
#app/models/result.rb
Class Result < ActiveRecord::Base
has_many :more_results, -> { select("#{Result.table_name}.*, count(#{ResultModel.table_name}.month) AS total")}
end
Upvotes: 1