【问题标题】:Rails 5: How to refactor this controller code to the model?Rails 5:如何将此控制器代码重构为模型?
【发布时间】:2017-01-10 23:40:04
【问题描述】:

我的控制器中有以下代码:

class VocabsController < ApplicationController
  before_action :require_login, except: [:index, :quiz, :answer, :result]

...
def quiz
  #Initiate score session
  session[:score] ||= 0
  #Initiate session to hold questions already asked
  session[:already_asked] ||= []
  #Total score
  session[:amount_questions] = Vocab.all.length

  #Get list of words that hasn't been asked before
  @left_words = Vocab.all.where.not(id: session[:already_asked])

  #Questions remaining
  @questions_remaining = @left_words.length - 4

  #Pick four words from leftover words list
  @four = @left_words.shuffle.take(4)

  #Create question variable if there are enough words left in list
  if @left_words.length >= 4
    @question = @four.first.word
  else
    redirect_to result_path
  end

  #save score to user database if all questions done and logged in
  if @questions_remaining == 0
    high_score = Score.new
    high_score.user_id = session[:user_id]
    high_score.score = session[:score] /  session[:amount_questions].to_f
    high_score.save
    redirect_to result_path
  end
end

def answer
  #Keep score and question id's already asked
  if params[:answer] == params[:orig]
    session[:score] += 1
    session[:already_asked] << params[:answer].to_i
    flash[:notice] = "You got it right!"
    redirect_to quiz_path
  else
    session[:already_asked] << params[:orig].to_i
    flash[:notice] = "Sorry, wrong answer!"
    redirect_to quiz_path
  end
end

我有以下模型:

class Vocab < ActiveRecord::Base
  validates :word, :definition, presence: true
end

我正在努力学习遵守瘦控制器胖模型范式,但由于 Rails 不允许会话变量传递给模型,我将如何将其重构为模型?

【问题讨论】:

  • 这个问题不属于这里,应该移到CodeReview。

标签: ruby-on-rails refactoring


【解决方案1】:

我认为在这种情况下遵循胖模型瘦控制器的最佳方法是为“测验”本身创建一个模型,然后“测验”将跟踪提出/回答的“词汇”问题。会话只会引用带有会话 ID 的测验。此外,您可能希望在会话完成后销毁“测验”或保留它们以进行测验分析...

【讨论】:

    猜你喜欢
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2019-11-08
    • 1970-01-01
    相关资源
    最近更新 更多