Rails中的游戏匹配资源?

时间:2015-11-28 20:19:20

标签: ruby-on-rails ruby

构建模型关系和嵌套资源以构建游戏的最佳方式是:用户(来自设计),游戏,玩家(加入游戏/用户的桌子)。我的问题是用户存在,但玩家需要与游戏同时创建。创建一个游戏也必须创建一个玩家,这是可能的,但感觉很棘手。有一个更好的方法吗?我想避免使用事务或过滤器来创建新资源。感谢。

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

1 个答案:

答案 0 :(得分:0)

我最终解决了这个问题,一起放弃了玩家模型并让用户拥有了很多游戏。

class Game < ActiveRecord::Base
  belongs_to :first_player, class_name: 'User', foreign_key: 'first_player_id'
  belongs_to :second_player, class_name: 'User', 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