0

我有三个模型:位置>热点>帐户

在我的位置模型中,我有这个:

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

我怎样才能在我的位置模型中做类似的事情 - 并且只显示我正在查看的特定位置的信息?我真的需要运行一个联接吗?

4

1 回答 1

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 字段的 Location 对象,以及您正在执行的聚合。

于 2012-04-23T10:35:33.967 回答