我在 Rails 应用程序中有三个模型: Game
表示正在玩的游戏的实例。 Player
表示游戏参与者的实例。 User
代表可以参与游戏的注册人。
每个Game
可以有多个Players
,每个User
可以有多个Players
(一个人可以参与多个立即进行游戏);但每个玩家
恰好处于一个游戏
中,并且恰好代表一个用户
。因此,我目前的关系如下。
class Game
has_many :players
end
class User
has_many :players
end
class Player
belongs_to :game
belongs_to :user
end
...players
表自然有 game_id
和 user_id
列,但是 games
和 users< /code> 没有外键。
我还想说明这样一个事实:每个游戏
都有许多用户
在玩;每个用户
都有他们正在玩的许多游戏
。我该怎么做?添加就够了吗
class Game
has_many :users, :through => :players
end
class User
has_many :games, :through => :players
end
I have three models in a Rails application: Game
represents an instance of a game being played. Player
represents an instance of a participant in a game. User
represents a registered person who can participate in games.
Each Game
can have many Players
, and each User
can have many Players
(a single person can participate in multiple games at once); but each Player
is in precisely one Game
, and represents precisely one User
. Hence, my relationships are as follows at present.
class Game
has_many :players
end
class User
has_many :players
end
class Player
belongs_to :game
belongs_to :user
end
... where naturally the players
table has game_id
and user_id
columns, but games
and users
have no foreign keys.
I would also like to represent the fact that each Game
has many Users
playing in it; and each User
has many Games
in which they are playing. How do I do this? Is it enough to add
class Game
has_many :users, :through => :players
end
class User
has_many :games, :through => :players
end
发布评论
评论(1)
你提出的建议应该足够了;现在,每个游戏应该有一个 users[] 数组,每个用户都有一个 games[] 数组。
http://guides.rubyonrails.org/association_basics.html# the-has-many-through-association
:has_many :through 基本上是典型多对多模型的扩展,其中您有一个中间表,其中包含每个相关实体的 id。然而,在 Rails 中,:has_and_belongs_to_many 关系不允许中间表本身成为一个实体,因为它除了充当两个相关模型之间的粘合剂之外没有任何意义。
:has_many :through 允许应用程序中的真实实体或模型(在您的情况下为玩家)充当其他两个(游戏、用户)之间的“粘合剂”,但也允许您操纵“玩家”,因为在本例中它确实包含重要信息。
希望这有帮助。
What you propose should be enough; Now, each game should have a users[] array, and each user has a games[] array.
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
:has_many :through is basically an extension of the typical many-to-many model where you have an intermediate table with ids for each one of the related entities. However, in Rails, the :has_and_belongs_to_many relationship doesn't allow for the intermediate table to be an entity in itself, in that it has no meaning other than serving as glue between the two related models.
:has_many :through allows a real entity or model in the application (in your case, players) to act as "glue" between two others (games, users) but also allowing you to manipulate "players" as in this case it does contain important information.
Hope this helps.