我想计算所有伤害的身体组的百分比,但无法弄清楚。
损伤模型:
class Injury < ActiveRecord::Base
belongs_to :player
belongs_to :season
has_one :injury_type
end
受伤类型型号:
class InjuryType < ActiveRecord::Base
has_one :body_group
end
身体组模型(无关联):
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。
您可能正在寻找如下所示的关联:
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