无法实例化服务对象

时间:2013-12-04 18:30:20

标签: ruby ruby-on-rails-4

我正在尝试为我的Rails应用程序进行一些重构。

我创建了一个QuizCompletion服务对象(app / services / quiz_completion.rb):

class QuizCompletion
  def initialize(quiz, user)
    @quiz = quiz
    @user = user
  end

  def pass?
    wrong_answers = 0
    @quiz.questions.each do |question|
      answer = @user.answers.where("question_id = ?", question.id).first
      if !answer.correct
        wrong_answers += 1
      end
    end
    if wrong_answers > 2
      return false
    else
      return true
    end
  end
end

然后在我的QuestionsController中,我尝试实例化服务对象:

class QuestionsController < ApplicationController
  before_filter :require_user
  def show
    @quiz = Quiz.find(params[:quiz_id])
    @question = Question.next(params[:id])
    if @question != nil
      redirect_to quiz_path(@quiz.id, question_id: @question.id)
    else
      evaluation = QuizCompletion.new(@quiz, current_user)  #instantiate Service Object!
      if evaluation.pass? 
        Quiz.complete(current_user, @quiz)
        redirect_to quiz_complete_path(@quiz.id)
      else
        redirect_to quiz_fail_path(@quiz.id)
      end
    end
  end

私人 端

但是,当我运行控制器测试时,我收到此错误:

Failure/Error: get :show, quiz_id: @quiz.id, id: question3.id
 NoMethodError:
   undefined method `stringify_keys' for #<Quiz:0x007fd781515300>

有人知道发生了什么事吗?为什么我不能在QuestionsController中实例化QuizCompletion对象?

感谢您的帮助,

安东尼

2 个答案:

答案 0 :(得分:0)

发现问题,显然问题在于我的服务对象的命名。 rails框架对quiz_completion.rb名称感到困惑,因为已存在Quiz(quiz.rb)模型。

所以我将服务对象的名称更改为Evaluation(evaluation.rb):

class Evaluation
  def initialize(quiz, user)
    @quiz = quiz
    @user = user
  end

  def pass?
    wrong_answers = 0
    @quiz.questions.each do |question|
      answer = @user.answers.where("question_id = ?", question.id).first
      if !answer.correct
        wrong_answers += 1
      end
    end
    if wrong_answers > 2
      return false
    else
      return true
    end
  end
end

当我从QuestionsController调用它时,这个名字也更有意义:

evaluation = Evaluation.new(@quiz, current_user)
  if evaluation.pass? 
    Quiz.complete(current_user, @quiz)
    redirect_to quiz_complete_path(@quiz.id)
  else
    redirect_to quiz_fail_path(@quiz.id)
  end

答案 1 :(得分:0)

我也无法实例化我的第一个服务对象 - 我收到此错误

uninitialized constant MyServiceObject (NameError)

我使用的是弹簧,不得不用spring stop来阻止它。之后它起作用了。