开发者

Help with associations in Rails

开发者 https://www.devze.com 2023-02-18 12:08 出处:网络
Let me describe what i want to do: There is a Matc开发者_如何转开发h model, which should have info about what players and what clans attended in it, with division of home players and clan and away pl

Let me describe what i want to do:

There is a Matc开发者_如何转开发h model, which should have info about what players and what clans attended in it, with division of home players and clan and away players and clan.

That is pretty easy, but there is another model: Summoner. In each match every player has different summoner and I need to do something like this: Match.find(1).players_home.find(1).Summoner.name to extract which summoner played player 1 in home team.

The point is: each player in each match can play with different summoner.

I hope I described it clearly.

Regards.


I'm not really sure about all your specifications regarding when an association is one or several, but I think something like this could be it:

class Match
  has_many :participations
  has_many :players, :through => :participations
end

class Participation
  belongs_to :match
  belongs_to :player
  belongs_to :summoner

  # also a team attribute to store either "home" or "away"
  scope :home, where(:team => "home")
  scope :away, where(:team => "away")
end

class Player
  belongs_to :clan
  has_many :participations
  has_many :matches, :through => :participations
end

class Summoner
  has_many :participations
end

In this setup every match has several participations. Every participation belongs to the player that is participating and also belongs to a summoner for that player and match. It can then be utilized perhaps like this:

In Controller

@match = Match.find(1)
@home_participations = @match.participations.home
@away_participations = @match.participations.away

In View

<h1>Home Players</h1>
<% @home_participations.each do |p| %>
  <p>Player: <%= p.player.name %>, Summoned by: <%= p.summoner.name %></p>
<% end %>

I hope this was at least somewhat what you where going for. Let me know if you are looking for something else.

0

精彩评论

暂无评论...
验证码 换一张
取 消