2015-06-18 138 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