给定以下数据库模式和Sequel模型,我如何选择一组按其命中求和的节点,同时将结果保留为模型实例,其中包含所有数据和工作方法?
Sequel.migration{ change{
create_table :nodes do
primary_key :id
String :name
# other columns
end
create_table :node_hits do
foreign_key :node_id, :nodes, null:false
Date :date, null:false
Integer :hits, null:false
primary_key [:node_id,:date]
end
end
class Node < Sequel::Model
one_to_many :node_hits
def is_awesome?
# use data known about the node
end
end
class NodeHit < Sequel::Model
many_to_one :node
end
以下代码似乎“工作”,但实际上未能具有该Node.is_awesome?
方法正常运行所需的属性(由于缺少有关节点的数据):
base = Node.filter(redacted:false)
recent = base.join(:node_hits,node_id: :id).filter{ date>Date.today-7 }
totals = recent.select_more{[ id, sum(hits)as(hits) ]}.group_by(:id)
puts totals.sql
#=> SELECT "id", sum("hits") AS "hits"
#=> FROM "nodes"
#=> INNER JOIN "node_hits" ON ("node_hits"."node_id" = "nodes"."id")
#=> WHERE (("name" != 'phrogz')
#=> AND ("archived" IS FALSE)
#=> AND ("date" > '2012-07-13'))
#=> GROUP BY "id"
totals.all.first.is_awesome?
#=> Error: `name` is nil for the Node instance.
如何获取 Sequel 通常为模型获取的任何字段?
我的最终要求是根据上周的点击总数以及该周的点击数获得前 N 个节点,同时允许 Node 实例具有完整功能(支持 Node 已知的所有数据)。