未定义的方法`<<&#; ##answer :: activerecord_relation:0x007fada31c7430>

时间:2016-03-16 12:16:59

标签: ruby-on-rails ruby model

您好我创建了一个控制器游戏来显示Q / A游戏

我被<<屏蔽了,这是代码

def play
    lvlup(lvl)
    if lvl == 1
      set_questions
    else
      get_questions
    end
    @answers = Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()")
    @answer ||= []
    @answers << question.answer
    @answers = @answers.shuffle
    render 'play'
  end

我创建了一个数组,并将相关答案放在我要显示的全局答案中4 Max。

为什么undefined在这里?

这是总代码

class GamesController < ApplicationController
attr_accessor :lvl

  def welcome
  end

  def congrat
  end

  def play
    lvlup(lvl)
    if lvl == 1
      set_questions
    else
      get_questions
    end
    @answers = Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()")
    @answer ||= []
    @answers << question.answer
    @answers = @answers.shuffle
    render 'play'
  end

  def loose
      @question = Question.find(params[:question])
      flash.now[:alert] = "Miss..."
      render 'loose'
  end

  def check
    @lvl = params[:lvl].to_i
    answer_id = params[:id].to_i
    question = Question.find(params[:question])
    if @lvl == lvlmax
      render action: 'congrat' and return
    elsif answer_id == question.answer_id
      flash.now[:notice] = "Well done !"
      play
    else answer_id != question.answer_id
      loose
    end
  end

  private

  def lvlup(value)
    @lvl = 1 + value.to_i
  end
  def lvlmax
    @lvlmax = Question.all.count
  end

  def set_questions
    @questionsids = []
    Question.all.shuffle.each do |d|
      @questionsids << d.id
    end
    cookies[:questions] = @questionsids
  end

  def get_questions
    @questions = cookies[:questions].split('&')
  end

  def questions
    @questions = cookies[:questions]
  end

  def question
    @question = Question.find(questions[lvl])
  end

end

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您正试图附加到@answers结果 - 这是一个ActiveRecord关系,您无法将数据附加到该数组。

在您设置.to_a的行的末尾添加@answers,以允许您附加到数组。

 @answers = Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()").to_a

答案 1 :(得分:0)

mtrolle的回答可能是正确的,但我怀疑为什么ActiveRecord::Relation默认情况下不会返回为Array。 (也是BroiStatse在评论中提到的。)

我也注意到我的本地设置存在同样的问题,但它总是归结为另一个问题。我在这里分享这个,以防你碰巧使用MySQL。

Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()")

返回ActiveRecord::Relation个对象。它转换为以下SQL:

SELECT `answers`.* FROM `answers` WHERE (id != ID) ORDER BY RANDOM() LIMIT 2

当我尝试在MySQL中运行相同的操作时,我得到:

ERROR 1305 (42000): FUNCTION database.RANDOM does not exist

显然MySQL没有RANDOM()功能,而是使用RAND()

转换ActiveRecord查询会相应地向我返回正确的数组:

Answer.where.not(id: question.answer_id).limit(2).order("RAND()")