【发布时间】:2014-12-27 18:45:38
【问题描述】:
我是 Rails 的初学者,所以请耐心等待哈哈。我正在尝试在 Rails 中创建一个 1v1 类型的匹配系统。下面列出了我尝试创建的过程以及我尝试的当前代码。
- 允许用户创建游戏。
- 允许其他用户加入该游戏。
- 如果两个用户在一场比赛中,则不允许其他用户加入。
匹配模型:
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