TL;博士:
所以我想我这样做:
@user.resources.each do |r|
#Something like this...
r.views.sum(:created_at, :group=>:resource_id) - r.views.sum(:updated_at, :group=>:resource_id)
end
现在,我知道我可以让它像这样工作:
r = Resource.first
time_sum_difference = r.views.sum {|v| v.updated_at.to_i - v.created_at.to_i}
但我宁愿让 ActiveRecord 为我计算它
编辑:废话,显然不能总结时间戳,需要就地计算差异
有一个更好的方法吗?我在正确的轨道上吗?(我将试验和更新这篇文章,直到我弄明白为止)
细节:
我有一个视图模型,它是资源和用户之间的连接表。
它具有标准时间戳:created_at 和 updated_at
我想获取用户提交的资源所花费的时间总和。
在我的资源模型中:
has_many :views, :class_name => 'UserResourceView'
然后对于视图:
class UserResourceView < ActiveRecord::Base
attr_accessible :resource_id, :user_id
belongs_to :resource
belongs_to :user
end
和用户:
class User < ActiveRecord::Base
has_many :resources
has_many :resource_views, :class_name => 'UserResourceView'
has_many :viewed_resources, :through => :resource_views, :source => :resource
...
end
更新:
u.resources.joins(:views).group('resources.id').select('sum(views.created_at) as s_ca, sum(views.updated_at) as s_ua, s_ca - s_ua as diff').first
Resource Load (0.7ms) SELECT sum(views.created_at) as s_ca, sum(views.updated_at) as s_ua, s_ca - s_ua as diff FROM "resources" INNER JOIN "user_resource_views" ON "user_resource_views"."resource_id" = "resources"."id" WHERE "resources"."user_id" = 1 GROUP BY resources.id LIMIT 1
ActiveRecord::StatementInvalid: PG::Error: ERROR: missing FROM-clause entry for table "views"
LINE 1: SELECT sum(views.created_at) as s_ca, sum(views.updated_at)...
^
: SELECT sum(views.created_at) as s_ca, sum(views.updated_at) as s_ua, s_ca - s_ua as diff FROM "resources" INNER JOIN "user_resource_views" ON "user_resource_views"."resource_id" = "resources"."id" WHERE "resources"."user_id" = 1 GROUP BY resources.id LIMIT 1
更新 2:
u.resources.joins(:user_resource_views).group('resources.id').select('sum(user_resource_views.created_at) as s_ca, sum(user_resource_views.updated_at) as s_ua, s_ca - s_ua as diff')
ActiveRecord::ConfigurationError: Association named 'user_resource_views' was not found; perhaps you misspelled it?
更新 3(更多信息):
从我的 schema.rb 文件:
create_table "user_resource_views", :force => true do |t|
t.integer "resource_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end