2009-12-30 55 views
0

我需要一些幫助來了解模型關係如何在rails上工作。讓我解釋一下這個場景。Rails加入三個模型並計算列的總和

我已經創建了3個模型。

  1. 屬性
  2. 單位
  3. 租金

這裏是映射他們的關係如何。

型號property.rb

class Property < ActiveRecord::Base 
     has_many :units 
     has_many :rents, :through=> :unit 
    end 

型號unit.rb

class Unit < ActiveRecord::Base 
    belongs_to :property 
    has_many :rents 
end 

型號rent.rb

class Rent < ActiveRecord::Base 
    belongs_to :unit 
end 

這裏是架構

 create_table "units", :force => true do |t| 
     t.integer "property_id" 
     t.string "number" 
     t.decimal "monthly_rent" 
     end 

create_table "rents", :force => true do |t| 
     t.integer "unit_id" 
     t.string "month" 
     t.string "year" 
     t.integer "user_id" 
     end 

好的,這是我的問題。比方說,我有2個屬性

  • 屬性的
  • 性質B

  • 屬性的具有單位A01,A02,A03
  • 性質B具有單位B01, B02,B03

我需要生成一份報告,顯示所有基於屬性和月份的所有優秀租金總和

因此,這裏是它應該是什麼樣子。 (表格格式)

  • 物業A - 月 - 出租SUM GOES HERE
  • 性質B - 月 - 出租SUM GOES HERE

所以我第一次拿到的所有屬性。但我真的不知道如何合併屬性和單位(我想我們不需要這部分的租金模型)並將它們打印在視圖中。有人可以幫助我做到這一點。謝謝

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 

回答

1

我認爲這樣的事情會對你有用。希望SQL大師會來檢查我的工作。我假設你的Property模型有一個「名稱」字段爲「屬性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 

這應該返回具有的屬性namemonth,並且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 

JOIN的所有三個表和GROUP BY能夠爲保護財產和每月每個唯一組合做SUM連接行(我們有包括年份,以便例如2008年12月不與2009年12月分組)。

+0

嗨喬丹,非常感謝你的職位。我嘗試了一些修改的例子,因爲我需要顯示總租金總額和總租金收到。即SUM(units.monthly_rent)和SUM(rents.total_amount)。但我總是隻獲得租金錶的總和。 – randika 2009-12-31 06:57:10

+0

@properties = Property.all:select =>「properties.name,rents.month,SUM(units.monthly_rent)AS rent_sum,SUM(rents.total_amount)AS rent_received」, :joins => {:units =>:租金}, :group =>「properties.id,rents.month,rents.year」,:conditions => {:properties => {:landlord_id => current_user.id},:rents => {:year => 2009,:month => 12}} – randika 2009-12-31 06:58:03

+0

您沒有提及租金錶上的「total_amount」列。我有點困惑。 – 2009-12-31 13:55:24