这是我的模特。
调查
class Survey < ActiveRecord::Base
belongs_to :user
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions, :reject_if => lambda {|a| a[:content].blank?}, :allow_destroy => true
问题:有一个is_correct(boolean)列,表示学生是否得到了正确的答案。
class Question < ActiveRecord::Base
belongs_to :survey
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
答案:教师检查进行调查(测试)时有正确的(布尔)列,并且有学生标记参加测试的user_answer(布尔)列。
class Answer < ActviveRecord::Base
belongs_to :question
我想在Answer模型中比较correct和user_answer,并在问题模型中保存is_correct的答案。
不仅有基本的CRUD方法用于生成问题和答案,还有三种额外的方法用于回答(GET)/评分(POST)检查,显示(GET)结果。我可以从rake路线的结果中检查这条路线没有问题。
更新问题:我更改了控制器和问题模型。
以下是调查控制器中的方法。
def answering
@survey = Survey.find(params[:id])
end
def grading
@survey = Survey.find(params[:id])
@survey.user_id = current_user.id
@survey.questions.each do |q|
q.auto_check
end
redirect_to results_survey_path(@survey)
end
def results
end
这是问题控制器。
def auto_check
answers.each do |a|
is_correct = true if a.user_answer and a.correct
self.save!
end
end
佣金路线的结果。
$ rake routes | grep survey
(in /home/seriousin/ClassCasts)
answering_survey GET /surveys/:id/answering(.:format) surveys#answering
grading_survey POST /surveys/:id/grading(.:format) surveys#grading
results_survey GET /surveys/:id/results(.:format) surveys#results
surveys GET /surveys(.:format) surveys#index
POST /surveys(.:format) surveys#create
new_survey GET /surveys/new(.:format) surveys#new
edit_survey GET /surveys/:id/edit(.:format) surveys#edit
survey GET /surveys/:id(.:format) surveys#show
PUT /surveys/:id(.:format) surveys#update
DELETE /surveys/:id(.:format) surveys#destroy
* 问题是我无法调用调查对象保存的用户输入。 *
我让结果方法为空。使用redirect_to,我不需要生成另一个调查对象。
def results
#@survey = Survey.where(params[:survey_id])
end
我认为没关系。因为我可以通过评分方法将调查对象作为参数传递。
def grading
@survey = Survey.find(params[:id])
@survey.user_id = current_user.id
@survey.questions.each do |q|
q.auto_check
end
redirect_to results_survey_path(@survey)
end
但结果是nil的'undefined method`name':NilClass'...我怎样才能使用包含用户输入的对象?
谢谢高级。
答案 0 :(得分:0)
auto_check
方法应该在问题模型中,而不是在问题控制器内。
答案 1 :(得分:0)
您的@survey.questions.each
为您提供了问题模型的实例,并且您正在调用QuestionsController
中定义的方法。如果auto_check
是Question
模型的成员,您将不会收到此错误。
如果您想在auto_check
中保留QuestionsController
方法,那么我认为您应该将question
实例作为参数传递如下:
def auto_check(question)
question.answers.each do |a|
is_correct = true if a.user_answer and a.correct
...
end
end
并按如下方式更新通话:
@survey.questions.each do |q|
auto_check(q)
end