0
我需要一些幫助來了解模型關係如何在rails上工作。讓我解釋一下這個場景。Rails加入三個模型並計算列的總和
我已經創建了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
嗨喬丹,非常感謝你的職位。我嘗試了一些修改的例子,因爲我需要顯示總租金總額和總租金收到。即SUM(units.monthly_rent)和SUM(rents.total_amount)。但我總是隻獲得租金錶的總和。 – randika 2009-12-31 06:57:10
@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
您沒有提及租金錶上的「total_amount」列。我有點困惑。 – 2009-12-31 13:55:24