Rails:我是否过度设计了这个测验和结果页面?

时间:2014-12-11 10:36:06

标签: ruby-on-rails ruby params

最近我一直试图获得一个测验页面指向结果页面(并且,感谢StanBoyet,我想我终于完成了它)。

我有一个用户模型和控制器,登录(使用Devise)一切正常。我有一个QuizAnswers模型和控制器以及数据库中的所有表。我也有一个ResultsController

这是我的routes.rb(注意资源):

Rails.application.routes.draw do
  devise_for :users

  root :to => 'home#index'

  get "elearning" => "home#elearning"
  get "howitworks" => "home#howitworks"
  get "leadershipstyles" => "home#leadershipstyles" 
  get "whattypeofleader" => "quizzes#new"
  get "showmetheskills" => "home#showmetheskills"
  get "safeguarding" => "home#safeguarding"
  get "toolsforthejob" => "home#toolsforthejob"
  get "whatnext" => "home#whatnext"
  get "congratulations" => "home#congratulations"
  get "teamwork" => "home#teamwork"
  get "facilitation" => "home#facilitation"
  get "planning" => "home#planning"
  get "communication" => "home#communication"

  resources :quizzes
  resources :results
  resources :quiz_answers

  resources :users do
    resources :posts  
  end
end

在我的测验表单中,我通过form_for @quiz_answers(可通过QuizAnswers#new操作访问):

def new
  @user = current_user
  @quiz_answer = current_user.quiz_answers.build
end

(我也试过,@quiz_answer = QuizAnswer.new

当我点击提交时,会触发QuizAnswers#create操作,如下所示:

def create 
  redirect_to results_path
end

哪些(rake路线告诉我)指向我设置的results#indexResultsController#index动作):

def index
  # in order to access all the results in our view...
  @results = QuizAnswer.find(current_user.id)
end

当我点击提交时,我收到错误:

找不到'id'= 35

的QuizAnswer

我有两个问题:

如何通过引用current_user的id来设置我的新QuizAnswers? (QuizAnswers有一个user_id属性,以及通常的id属性)。

其次,这一切都是可怕的过度设计还是仅仅是“Rails方式”? (如果我做错了,请随意解释我应该如何做'对'。)

1 个答案:

答案 0 :(得分:0)

这条线很奇怪:

@results = QuizAnswer.find(current_user.id)

您需要将其更改为

@results = QuizAnswer.where(user_id: current_user.id)
#or
@results = current_user.quiz_answers