我正試圖建立一個遊戲,你猜數字。 問題是,如果你犯了一個錯誤,它會將你重定向到一個排行榜(mvc)表單,你在其中輸入你的名字加上它預先填充了來自不同控制器(遊戲)的會話數據並提交到數據庫中。訪問來自不同控制器的變量
@round & @points是我想要訪問並存儲爲分數和級別的兩個變量。
class ApplicationController < ActionController::Base
before_filter :set_current_account
def set_current_account
# set @current_account from session data here
Game.current = @round
end
protect_from_forgery
end
-
class Leaderboard < ActiveRecord::Base
cattr_accessor :current
end
# == Schema Information
#
# Table name: leaderboards
#
# id :integer not null, primary key
# name :string(255)
# score :string(255)
# level :string(255)
# created_at :datetime
# updated_at :datetime
#
-
class GameController < ApplicationController
def index
@games = Game.all
respond_to do |format|
format.html
end
end
def start_game
session[:round] ||= 1
session[:points] ||= 0
@round = session[:round]
@points = session[:points]
end
def generate_round
numbers = Array.new(6){rand(9)}
@addition = []
@display = numbers
numbers.inject do |s, i|
@addition << s + i
@addition.last
end
end
def next_round
session[:round] += 1
session[:points] += 1200
@round = session[:round]
@points = session[:points]
end
def destroy_sessions
session[:round] = nil
session[:points] = nil
session[:addition] = nil
@round = session[:round]
@points = session[:points]
@addition = session[:addition]
start_game
end
def submit_name
@game = Game.new(params[:game])
respond_to do |format|
if @game.save
format.html { redirect_to(leaderboard_path, :notice => 'Score was added successfully.') }
else
format.html { render :action => "new" }
end
end
end
def game_over
redirect_to :controller => 'leaderboards', :action => 'new' and return
end
感謝您的回答,它似乎工作後,我取代了一些東西。對於任何看起來有效的工作 - > redirect_to:controller =>'leaderboards',:action =>'new',:level => session [:round],:score => session [:points]並返回 –
Woot。對不起,我從某處獲取了redirect_to,只是添加了參數。我應該更加小心。 :) –