2015-06-18 196 views
0

我想計算所有受傷人羣的百分比,但無法弄清楚。。其中嵌套屬性屬性的屬性=字符串

損傷模型:

class Injury < ActiveRecord::Base 
    belongs_to :player 
    belongs_to :season 
    has_one :injury_type 
end 

InjuryType型號:

class InjuryType < ActiveRecord::Base 
    has_one :body_group 
end 

BodyGroup模型(無關聯):

class BodyGroup < ActiveRecord::Base 
end 

我打印受傷的總數是這樣的:

= Injury.all.order('start_date ASC').count 

... 但後來我卡住了。在我看來,這應該是超級簡單的,如下所示:

= Injury.where(injury_type.body_group_id => 1).count 

我該如何打印身體組有id 1的受傷人數?我究竟做錯了什麼?我已經試過這樣:

= Injury.joins(:body_group => :injury_type).where(:body_group => {:id => 1}) 

...但這只是給了我#<Injury::ActiveRecord_Relation:0x007ff14c929bf0>,我不能變成一個.Count之間或的.sum。

+0

你應該在'where'子句中使用的表的名稱,以及'includes' /'joins'中的關係名稱(請參閱http://stackoverflow.com/questions/23633301/how-to-query-a-model-based-on-attribute-of-another-model-這屬於這個fi/23633352#23633352和類似的問題鏈接在這個答案) – MrYoshiji

回答

3

您概率尋找像下面的關聯:

class Injury < ActiveRecord::Base 
    belongs_to :injury_type 
end 

class InjuryType < ActiveRecord::Base 
    belongs_to :body_group 
    has_many :injuries 
end 

class BodyGroup < ActiveRecord::Base 
    has_many :injury_types 
end 

通過這種方式,可以簡化查詢:

Injury.joins(:injury_type).where(body_group_id: 1).count 
+0

這不需要InjuryType有一個傷害標識,意思是每個傷害都有一個新的傷害類型? –

+0

如果我添加這些關聯並使用您編輯的片段,它會導致'PG :: UndefinedColumn:ERROR:column injury_types.injury_id does not exist' –

+0

它應該是:'一個'受傷'屬於'受傷類型'(假設有一個專欄)。而''''''具有很多'明顯''受傷'。例如,你可能會有20人受傷,這是骨折。 – Biketire