Fred Fickleberry III
Fred Fickleberry III

Reputation: 2519

Select multiple associated objects in one query

I am using Postgresql and my player model has some associations such as:

class Goal < ActiveRecord::Base
  belongs_to :player
end

class Substitution < ActiveRecord::Base
  belongs_to :player
end

class Penalty < ActiveRecord::Base
  belongs_to :player
end

In my view I'm listing the lineup of a team, and behind each player's name I want to display the goals they scored, the penalties they received and the minute they were substituted (if any).

1. Player A - goal_icon (minute) goal_icon(minute) yellow_card_icon (minute) 
2. Player B - yellow_card_icon (minute) 
3. Player C - goal_icon (minute) substituted (minute)

So I obviously want to:

How do I do this?

Upvotes: 0

Views: 280

Answers (1)

clyfe
clyfe

Reputation: 23770

I would implement Single Table Inheritance or Multiple Table Inheritance and then be able to call: @player.events.sort(:minute).

For example with STI:

class Player < AR
  has_many :events
end

class Event < AR
  belongs_to :player
end

class Goal < Event end
class Substitution < Event end
class Penalty < Event end

@player.events.sort(:minute) # [#Goal, #Goal, #Penalty]

Upvotes: 1

Related Questions