访问来自不同控制器的变量

时间:2011-07-14 18:46:37

标签: ruby-on-rails ruby rails-activerecord

我正在尝试构建一个你猜数字的游戏。 问题是,如果你犯了一个错误,它会将你重定向到一个排行榜(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

2 个答案:

答案 0 :(得分:1)

我还没有读完整个内容,但如果你只是想访问这些变量,你可以将它们作为参数传递。

  1. 将这些值作为参数传递给game_over

  2. 使用此选项重定向

  3. redirect_to:controller =&gt; '排行榜',:action =&gt; 'new'并返回,:round =&gt; params [:round],:points =&gt; PARAMS [:分]

    或者,您可以保持会话直到新游戏开始或分数记录到排行榜。

答案 1 :(得分:0)

我认为你在这里采取了一种甚至不起作用的方法。 Rails MVC框架围绕着每个请求独立服务的原则构建,理论上,除了通过传递的params之外,没有从一个请求到下一个请求的状态转移,存储在数据库中的记录和持久用户session

要像设计基于Web的应用程序一样,单进程,单用户,单会话程序是错误的。使用单身,就像你的cattr_accessor current一样,会有问题,因为它在请求之间共享,而不是在不同的Rails实例之间共享,其中通常有很多。

更紧密地映射到indexnewcreateshoweditupdate和{{1}的REST标准}} 有助于。例如,destroy应为start_game,而create应为destroy_sessions

从您的设计中不清楚每个游戏是由多个用户共享,还是单独为每个用户创建,因此很难说更多关于如何解决您的问题。

相关问题