【问题标题】:Resources for Game Match in Rails?Rails 中的游戏匹配资源?
【发布时间】:2015-11-29 04:49:29
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    我最终通过完全取消玩家模型并让用户拥有_many :games 解决了这个问题。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多