我有三个型号:位置>热点>帐户
在我的位置模型中,我有这个:
has_many :hotspots
has_many :accounts, :foreign_key => :calledstationidclean, :through => :hotspots
我正在尝试显示每个位置的帐户模型的一些摘要数据。
以下工作正常:
scope :location_history, lambda { |id|
joins('INNER JOIN hotspots b ON locations.id = b.location_id INNER JOIN account ON b.mac = account.calledstationidclean')
.where(:id => id)
.select("count(locations.id) AS sessions_count, sum(account.acctoutputoctets) AS downloads, sum(account.acctinputoctets) AS uploads, count(distinct account.callingstationid) AS unique_user")
}
但我需要进行一些计算,我无法弄清楚如何做到这一点。
通常,在帐户模型中,我可以执行以下操作:
def self.session_time
Account.sum("acctsessiontime")
end
def self.average_session
self.session_time / Account.count
end
我如何在我的位置模型中做类似的事情 - 并且只显示我正在查看的特定位置的信息?我真的需要运行联接吗?
答案 0 :(得分:1)
是的,你必须加入。
scope :location_history,
lambda { |id| joins(:hotspots, :accounts).where(:id => id).
select("sum(account.acctsessiontime) as acctsessiontime, count(locations.id) AS sessions_count, sum(account.acctoutputoctets) AS downloads, sum(account.acctinputoctets) AS uploads, count(distinct account.callingstationid) AS unique_user")
}
顺便说一下,您可以使用一个组并将所有这些组合到位置的记录中。
scope :with_history,
lambda { |id| joins(:hotspots, :accounts).where(:id => id).
select("locations.*, sum(account.acctsessiontime) as acctsessiontime, count(locations.id) AS sessions_count, sum(account.acctoutputoctets) AS downloads, sum(account.acctinputoctets) AS uploads, count(distinct account.callingstationid) AS unique_user")
}
这将返回包含所有位置字段的Location对象,以及您正在进行的聚合。