0

I want to calculate the percentage of body groups for all injuries, but can't figure it out.

Injury model:

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

InjuryType model:

class InjuryType < ActiveRecord::Base
  has_one :body_group
end

BodyGroup model (no association):

class BodyGroup < ActiveRecord::Base
end

I print the total number of injuries like this:

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

...but then I'm stuck. In my mind this should be super simple, something like:

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

How can I print the number of injuries where body group has id 1? What am I doing wrong? I've tried this:

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

...but this only gives me #<Injury::ActiveRecord_Relation:0x007ff14c929bf0>, which I can't turn into a .count or a .sum.

Ix Techau
  • 71
  • 7
  • you should use the table's name in the `where` clause, and the relation name in the `includes`/`joins` (see http://stackoverflow.com/questions/23633301/how-to-query-a-model-based-on-attribute-of-another-model-which-belongs-to-the-fi/23633352#23633352 and the similar questions linked in this answer) – MrYoshiji Jun 18 '15 at 14:24

1 Answers1

3

You are probability looking for an association like the below:

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

In this way, you can simplify the query:

Injury.joins(:injury_type).where(body_group_id: 1).count
gabrielhilal
  • 10,660
  • 6
  • 54
  • 81
  • Doesn't this then require InjuryType to have an injury_id, meaning a new InjuryType for every Injury? – Ix Techau Jun 18 '15 at 14:23
  • If I add those associations and use your edited snippet, it results in `PG::UndefinedColumn: ERROR: column injury_types.injury_id does not exist` – Ix Techau Jun 18 '15 at 14:27
  • It should be: 'An `injury` belongs to an `injury type` (assuming that there's a column for that). And an `injury_type` has many `injuries` obviously'. You can have 20 injuries which are broken bones for instance. – Biketire Jun 18 '15 at 14:29
  • @Fietsband: I totally agree ;) @Ix Techau can you explain the association between `injury` and `injury_type` – gabrielhilal Jun 18 '15 at 14:34
  • Ok, those associations make more sense. I've changed them so it's now: Injury belongs_to InjuryType, and InjuryType has_many Injuries. If I now do `Injury.joins(injury_type: :body_group).where("body_groups.id = 1").count`, it doesn't break but it's always 0. If I do a :pluck, the array is empty. – Ix Techau Jun 18 '15 at 14:37
  • you need to fix the association between `InjuryType` and `BodyGroup` as well – gabrielhilal Jun 18 '15 at 14:41
  • Yup, that did it. Thanks! – Ix Techau Jun 18 '15 at 14:48