2011-07-14 52 views
0

我正試圖建立一個遊戲,你猜數字。 問題是,如果你犯了一個錯誤,它會將你重定向到一個排行榜(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 

回答

1

我還沒有讀完整件事,但如果你只是想訪問這些變量,你可以將它們作爲參數傳遞。

  1. 傳遞這些值代入game_over作爲PARAMS

  2. 使用此重定向

redirect_to的:控制器=> '排行榜',:動作=> '新' 和返回,: round => params [:round],:points => params [:points]

或者,您可以保持會話,直到開始新遊戲或將分數記錄到排行榜。

+0

感謝您的回答,它似乎工作後,我取代了一些東西。對於任何看起來有效的工作 - > redirect_to:controller =>'leaderboards',:action =>'new',:level => session [:round],:score => session [:points]並返回 –

+0

Woot。對不起,我從某處獲取了redirect_to,只是添加了參數。我應該更加小心。 :) –

0

我想你已經採取的做法在這裏,甚至不應該工作。 Rails MVC框架圍繞每個請求獨立服務的原則構建,理論上,除了通過傳入的params,存儲在數據庫中的記錄和永久用戶session之外,不存在從一個請求到下一個請求的狀態轉移。

要設計一個基於Web的應用程序,就像您可能會使用單進程單用戶單會話程序一樣,這是一個錯誤。使用單身人士,比如你的cattr_accessor,被稱爲current將會有問題,因爲它是在請求之間共享的,而不是在Rails的不同實例之間共享的,其中通常有很多實例。

映射更緊密地的indexnewcreateshoweditupdatedestroy REST的標準會有所幫助。例如start_game應該是createdestroy_sessions應該可能是destroy

從您的設計中可以看出,如果每個遊戲都是由多個用戶共享的,或者它們是爲每個用戶單獨創建的,所以很難多說出如何解決問題。

+1

我知道我已經採取了錯誤的方法來構建這件事。我基本上嘗試將純Ruby的某些東西移植到rails中,並實施各種解決方法以實現其功能。在這一點上,我只是想添加最後一項功能。在週末,我打算坐下來開始學習Rails。 –