【问题标题】:1v1 game system rails1v1游戏系统导轨
【发布时间】:2014-12-27 18:45:38
【问题描述】:

我是 Rails 的初学者,所以请耐心等待哈哈。我正在尝试在 Rails 中创建一个 1v1 类型的匹配系统。下面列出了我尝试创建的过程以及我尝试的当前代码。

  1. 允许用户创建游戏。
  2. 允许其他用户加入该游戏。
  3. 如果两个用户在一场比赛中,则不允许其他用户加入。

匹配模型:

class Match < ActiveRecord::Base
belongs_to :user

结束

比赛控制器:

class MatchesController < ApplicationController

before_filter :find_match, only: [:show, :join]

def index
    @matches = Match.all
end

def new
    @match = Match.new
end

def create
    @match = current_user.matches.new(match_params)

    if @match.save
        redirect_to root_url, notice: 'created.'
    else
        render('new')
    end
end

def join
    if @match.update_attributes(:opponent_id => current_user.id)
        redirect_to root_url, notice: 'joined.'
    else
        render('new')
    end
end

private
    def find_match
        @match = Match.find(params[:id])
    end
    def match_params
        params.require(:match).permit(:user_id, :opponent_id)
    end

结束

用户模型:

class User < ActiveRecord::Base
     has_many :matches

结束

匹配迁移:

    create_table :matches do |t|
    t.string :match_title
    t.integer :user_id
    t.integer :opponent_id
    t.boolean :joinable
  t.timestamps

谢谢。

【问题讨论】:

  • 你没有问任何问题。

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

您的代码有一些小错误。在“加入”方法中,您应该更改条件:

def join

    if @match.joinable
        @match.update_attributes(:opponent_id => current_user.id, :joinable => false)
        redirect_to root_url, notice: 'joined.'
    else
        render('new')
    end
end

并在 'create' 方法中添加一行:

def create
    @match = current_user.matches.new(match_params)

    @match.joinable = true

    if @match.save
        redirect_to root_url, notice: 'created.'
    else
        render('new')
    end
end

现在,用户无法加入已经有 2 名玩家的比赛。

【讨论】:

  • 我以为我离得很远哈哈。谢谢,效果很好!
  • 我还有一个问题。我如何能够从“opponent_id”访问用户信息?
  • @opponent = User.find(opponent_id)
猜你喜欢
  • 2020-07-17
  • 2011-03-15
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
相关资源
最近更新 更多