简体   繁体   中英

.where attribute of nested attribute attribute = string

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM