[英]RoR3 Model associations (Game belongs_to two Players)
我真的是Ruby on Rails 3的新手 ,並且正在開發一個簡單的國際象棋游戲應用程序。 我計划創建以下模型:
rails g model Player name:string
rails g model Game player_id_white:int player_id_black:int title:string
rails g model Comment player_id:int game_id:int comment_data:text
rails g model Move game_id:int player_id:int move_data:string
假設它們都有:id:int:primary_key,created_at:datetime,updated_at:datetime。 我還省略了“ password_hash”等字段。 我的問題是關聯,而不是我需要什么才能使應用正常工作。
class Player < ActiveRecord::Base
has_many :games #some have player_id_black, others as player_id_white
has_many :comments
has_many :moves
end
class Game < ActiveRecord::Base
has_many :comments
has_many: moves
**belongs_to :player1??**
**belongs_to :player2??**
end
class Comment < ActiveRecord::Base
belongs_to :player
belongs_to :game
end
class Move < ActiveRecord::Base
belongs_to :player
belongs_to :game
end
問題:
1)我想將一個游戲鏈接到兩個玩家,如何指定這種關系?
2)我是否必須在“ rails generate model”中指定像game_id:int之類的東西,還是在進行關系時(belongs_to:player,has_many:games)隱式?
謝謝!
鑒於上述遷移,您需要按以下步驟設置游戲模型:
class Game < ActiveRecord::Base
has_many :comments
has_many :moves
belongs_to :white_player, :class_name => 'Player', :foreign_key => 'player_id_white'
belongs_to :black_player, :class_name => 'Player', :foreign_key => 'player_id_black'
end
這將使用您的自定義外鍵,並使您可以將每個關聯作為一個單獨的Emirates_to調用來鏈接!
另外,如果您希望Rails“猜測” foreign_key設置,則需要像下面這樣設置遷移:
rails g model Game white_player_id:integer black_player_id:integer title:string
如果這樣做,您仍然需要為每個屬植物調用指定:class_name =>'Player'選項。
我在同一條船上:Rails的新手,並構建了一個國際象棋應用程序。 我開始使用玩家與游戲之間的has_and_belongs_to_many關系,但是我不知道如何用這種方式正確地為白人和黑人玩家角色建模。
我最終使用了與roboles建議的方法不同的方法,因為我需要一種跟蹤從玩家到游戲的關系的方法。
首先,我添加了第三個名為Seats的模型,然后將Player和Game模型設置為具有has_many:through關系,例如:
class Game < ActiveRecord::Base
has_many :seats
has_many :players, :through => :seats
end
class Player < ActiveRecord::Base
has_many :seats
has_many :games, :through => :seats
end
class Seat < ActiveRecord::Base
belongs_to :game
belongs_to :player
end
這將建立模型,以便game.players和player.games起作用。
為了跟蹤白人和黑人球員,我在座位表中添加了顏色列:
create_table "seats", :force => true do |t|
t.integer "player_id"
t.integer "game_id"
t.integer "color"
t.datetime "created_at", :null => false
end
然后,在游戲模型中,我添加了一些輔助方法,以便可以通過game.white_player獲取白人玩家並通過game.white_player = foo進行設置
class Game < ActiveRecord::Base
...
def white_player
Player.joins(:games).where(:seats => {:color => 0, :game_id => self.id}).first
end
def white_player=(player)
self.players << player
s = self.seats.find_by_player_id(player)
s.color = 0
s.save
end
我不確定這是否是最好的方法,但似乎符合我的要求:
game.players # returns game's players
player.games # returns player's games
game.white_player # returns the white player
game.white_player = player # sets the white player
我很想知道任何改進的方法。
在您的游戲類中,添加2個字段,例如:
belongs_to :player_one, :class_name => "Player"
belongs_to :player_two, :class_name => "Player"
因此,這意味着您的數據庫中有2個整數字段player_one int, player_two int
其他模型不必更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.