鉴于以下数据库模式和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实例具有全功能(支持所有数据)以节点而闻名。
答案 0 :(得分:2)
您需要从节点表中选择所有列。这是我使用的:
totals = Node.filter(redacted:false).
select_all(:nodes).
select_more{sum(hits).as(hits)}.
group(:nodes__id).
join(:node_hits, node_id: :id).
filter{ date>Date.today-7 }