0
構建模型關係和嵌套資源以構建遊戲的最佳方式是:用戶(來自設計),遊戲,玩家(連接遊戲/用戶表)。我的問題是用戶存在,但玩家需要與遊戲同時創建。創建一個遊戲也必須創建一個球員,這是可能的,但感覺噁心。有一個更好的方法嗎?我想避免使用事務或過濾器來創建新資源。謝謝。Rails中的遊戲匹配資源?
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable
devise :omniauthable, :omniauth_providers => [:facebook, :twitter]
has_many :games
end
class Player < ActiveRecord::Base
validates :user_id, uniqueness: { scope: :game,
message: "can't join your own game" }
belongs_to :user
belongs_to :game
has_one :board
has_many :ships
end
class Game < ActiveRecord::Base
belongs_to :first_player, class_name: 'Player', foreign_key: 'first_player_id'
belongs_to :second_player, class_name: 'Player', foreign_key: 'second_player_id'
has_one :first_player_board, through: :first_player, source: :board
has_one :second_player_board, through: :second_player, source: :board
end