2011-05-01 44 views
0

這裏是我的模型:如何從我的表得到Rails相關數據3

class Food < ActiveRecord::Base 
    has_many :lists 
    has_many :costs, :through => :lists 
end 

class List < ActiveRecord::Base #each food can have multiple lists, ordered by date 
    belongs_to :food 
    has_many :costs, :dependent => :destroy 
    accetps_nested_attribute_for :costs, :allow_destroy => true 
end 

class Cost < ActiveRecord::Base #costs are nested inside of a list 
    belongs_to :food 
    belongs_to :list 
end 

這裏是我的架構(你需要看到的部分):

create_table "foods", :force => true do |t| 
    t.integer "food_id" 
    t.string "name" 
    t.string "type" # this is where I can choose a 'fruit' or a 'vegetable' 
end 

create_table "lists", :force => true do |t| 
    t.integer "food_id" 
    t.integer "quarter" #this is how lists are ordered 
    t.integer "year" 
end 

create_table "costs", :force => true do |t| 
    t.integer "amount" 
    t.integer "list_id" 
    t.integer "food_id" 
end 

我想什麼做的是能夠通過我的表格篩選以顯示基於特定標準的總成本或平均成本。因此,例如,我想知道所有水果在一段時間內的總成本或平均成本(來自成本模型的金額屬性)(在列表模型中按季度和年份排序)。這更清楚嗎?感謝迄今爲止的反饋。

+1

它將大大有助於理解q如果你用模型的實際代碼替換你的課程的散文描述,那麼這個問題更好。 – Thilo 2011-05-01 19:35:06

+0

編輯你的問題,並正確的結構。這很難理解 – 2011-05-01 20:34:50

+0

@Thilo&@Jatin - 我編輯了我的問題。希望它更清楚。 – FattRyan 2011-05-01 21:53:35

回答

1

您需要先修復模型。您擁有屬於List和Food的成本,但在您的遷移中沒有外鍵。通常,如果模型A:屬於模型B,則模型A的表需要b_id作爲外鍵。

一旦你修復了這個問題,既然你想要一個聚合,你必須建立一個基於具有聚合值的模型的查詢 - 在本例中爲Cost。要限制爲僅包括與食物有特定屬性相關聯的那些成本 - 所以使用方法鏈是這樣的(假設你使用的Rails 3):

# average cost of all fruit 
Cost.includes(:food).where('foods.type = ?', 'fruit').average(:amount) 

要逐年限制這種與季度得到稍微複雜一些,但是工作原理相同,但爲了給你提供可靠的建議,你需要首先修復你的模型。我建議這兩個指南讀了起來:

編輯

你的編輯後,試試這個(未經測試):

Cost.includes(:food, :list).where('foods.type = ? AND lists.year = ? AND lists.quarter = ?', 'fruit', 2011, 1).average(:amount) 
+0

@ Thilo - 感謝您的反饋。我想保持儘可能短,但我有列表和成本的_id字段將所有內容連接在一起。我的嵌套表單工作得很好,當我創建一個新列表時,它將food_id傳遞給列表以及成本。那麼我又如何按季度和年度過濾呢? – FattRyan 2011-05-02 00:44:26

+0

這很好。然而,我確實有這個問題的更復雜的版本,因爲你對這個問題有正確的答案,所以我希望你們看一看。 [問題在這裏](http://stackoverflow.com/questions/5862828/rails-3-complex-data-mining) – FattRyan 2011-05-02 21:48:03

相關問題