在控制器中调用类方法

时间:2014-03-20 19:57:35

标签: ruby-on-rails ruby

我有一个游戏模型和一个GamesController。这些代表了一系列体育赛事。然后我有一个短语模型,它只是一组随机短语。短语不属于任何游戏,游戏也没有任何短语。但是,我确实想在Games#index中显示一个随机短语。

我以为我会在Game模型上使用类方法来引入短语:

class Game < ActiveRecord::Base
  def self.pull_phrase
    Phrase.all.shuffle.limit(1)
  end
end

然后在GamesController我有:

class GamesController < ApplicationController
  def index
    @games = Game.all
    @next_games = Game.where(["date > ?", Time.now]).all
    @schedule = @next_games[0..4]
  end

  def phrases
    @phrase = Game.pull_phrase
  end   
end

然后在我看来,我只想输出@phrase

我没有收到任何错误,但看起来我没有任何错误。

谢谢!

1 个答案:

答案 0 :(得分:2)

我认为您需要在索引操作中设置变量@phrase。在@phrase=Game.pull_phrase内拨打GamesController#index

def index
    @games = Game.all
    @next_games = Game.where(["date > ?", Time.now]).all
    @schedule = @next_games[0..4]
    @phrase = Game.pull_phrase
    ##Alternative
    @phrase = Phrase.all.sample
end
class Game < ActiveRecord::Base
  def self.pull_phrase
    Phrase.all.sample
  end
end

注意您甚至不需要声明Game#pull_phrase类功能,因为这种情况非常简单(参见替代方案)

相关问题