2012-01-25 52 views
0

這是一個Ruby 1.9.3/Rails 3.2項目。ActiveRecord查詢計數關係數

比方說,我有一個名爲Role模型,以及一個名爲Employee模型,通過has_many/belongs_to關係鏈接。一個角色有很多員工,一個員工屬於一個角色。這兩種模型都屬於擁有許多員工和角色的Store對象。

每個角色都有一個target_headcount屬性,表示該位置的理想僱員人數。從那裏,我有一個像下面的方法對Role

class Role < ActiveRecord::Base 
    # ... 

    # Number of employees currently filling this role. 
    def current_headcount 
    employees.count 
    end 

    # Number of headcount above or below the target. 
    def variance 
    current_headcount - target_headcount 
    end 
end 

通常情況下,我需要獲得針對其存在開放人數角色的集合。不過,我現在用的meta_search,這需要一個ActiveRecord::Relation對象RubyGem

def self.open_headcount 
    all.select { |r| r.variance < 0 } 
end 

:我在做這個使用下面的類方法的作用。我想將open_headcount從類方法更改爲範圍,以便它返回一個ActiveRecord::Relation對象,但我不確定它是否可行。

+0

您是否願意將「open_headcount」作爲整數添加到角色表中? –

+0

@JesseWolgamott我想避免它,但我想如果必須我可以在'Employee'上使用'after_create'和'after_update'來設置'Role#open_headcount'。 – clem

回答

0

這是超舊的,但FTR我可能可以通過使用SQL查詢來計算角色的僱員數量並從中減去目標列的值。