Ruby on rails Rails连接三个模型并计算列的和

Ruby on rails Rails连接三个模型并计算列的和,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我需要一些帮助来理解模型关系在rails上是如何工作的。让我解释一下情况 我已经创建了3个模型 性质 单位 租 下面是它们的关系映射方式 模型属性.rb class Property < ActiveRecord::Base has_many :units has_many :rents, :through=> :unit end 好的,这是我的问题。假设我有两个属性 财产A 财产B 及 物业A有A01、A02、A03单元 物业B的单元为B01、B

我需要一些帮助来理解模型关系在rails上是如何工作的。让我解释一下情况

我已经创建了3个模型

性质 单位 租 下面是它们的关系映射方式

模型属性.rb

 class Property < ActiveRecord::Base
      has_many :units
      has_many :rents, :through=> :unit
    end
好的,这是我的问题。假设我有两个属性

财产A 财产B 及

物业A有A01、A02、A03单元 物业B的单元为B01、B02、B03 我需要生成一份报告,根据物业和月份显示所有未付租金的总和

这就是它应该是什么样子。表格格式

物业A-12月-租金总额在这里 物业B-12月-租金总额到此为止 所以我先得到了所有的属性。但是我真的想不出一个合并房产和单元的方法,我想我们不需要这部分的租金模型并在视图中打印它们。有人能帮我做这个吗。谢谢

  def outstanding_by_properties

    @properties = Property.find(:all)
    @units = Unit.find(:all,:select=>"SUM(monthly_rent) as total,property_id",:conditions=>['property_id IN (?)',@properties])
  end

我想这样的东西对你会有用的。希望SQL专家会来检查我的工作。我假设您的属性模型有一个属性a的名称字段,等等-您应该将其更改为您的字段所调用的名称

def outstanding_by_properties
  Property.all  :select => "properties.name, rents.month, SUM(units.monthly_rent) AS rent_sum",
                :joins => { :units => :rents },
                :group => "properties.id, rents.month, rents.year"
end
这将返回属性为name、month和rent_sum的属性对象数组

它基本上映射到以下SQL查询:

SELECT properties.name, rents.month, SUM(units.monthly_rent) AS rent_sum
FROM properties
  JOIN units ON properties.id = units.property_id
  JOIN rents ON units.id = rents.unit_id
GROUP BY properties.id, rents.month, rents.year

联接将所有三个表中的行和分组方式连接起来,这样就可以对每个唯一的属性和月份组合进行求和,我们必须包括年份,例如2008年12月不会与2009年12月一起分组。

Hi Jordan,非常感谢你的帖子。我尝试了你的例子,做了一些修改,因为我需要显示租金总额和收到的租金总额。即SUMunits.monthly_rent和SUMrents.total_amount。但是我总是只得到租金总额表。@properties=Property.all:select=>properties.name,rents.month,SUMunits.monthly\u rent AS rent\u SUM,SUMrents.total\u amount AS rent\u received,:joins=>{:units=>:rents},:group=>properties.id,rents.month,rents.year,:conditions=>{:properties=>{:lown\u id=>current\u user.id},:rents=>{:year=>2009,:month=>12}你没有提到租金表上的“总金额”列。我有点困惑。对不起,是的,我只是从原始代码中排除了一些部分,只是为了让你们保持简单。我使用租金表来保留已支付的租金。我知道我也可以从单位表中获得它。但在当前设置中,当用户支付租金时,我插入了rt单位id、总金额、月、年。租金.total金额的值始终与单位.monthly租金相同。
  def outstanding_by_properties

    @properties = Property.find(:all)
    @units = Unit.find(:all,:select=>"SUM(monthly_rent) as total,property_id",:conditions=>['property_id IN (?)',@properties])
  end
def outstanding_by_properties
  Property.all  :select => "properties.name, rents.month, SUM(units.monthly_rent) AS rent_sum",
                :joins => { :units => :rents },
                :group => "properties.id, rents.month, rents.year"
end
SELECT properties.name, rents.month, SUM(units.monthly_rent) AS rent_sum
FROM properties
  JOIN units ON properties.id = units.property_id
  JOIN rents ON units.id = rents.unit_id
GROUP BY properties.id, rents.month, rents.year