我的控制器中有以下if
语句,如果用户尚未完成per_quiz#new
,则会将用户引导至per_quiz
页面,如果per_quiz#edit
页面他们采取了一个:
def new
@per_quiz = current_user.build_per_quiz
if current_user.per_quiz != nil
redirect_to edit_per_quiz_path(current_user.per_quiz)
end
end
我作为未使用localhost
的用户访问per_quiz
,我可以通过console
告诉他们:
[2] pry(main)> User.first.per_quiz
User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
PerQuiz Load (0.2ms) SELECT "per_quizzes".* FROM "per_quizzes" WHERE "per_quizzes"."user_id" = ? LIMIT 1 [["user_id", 1]]
=> nil
然而,当我尝试访问该页面时,我得到一个错误(我认为)看起来像是被导向if
语句的错误分支:
No route matches {:action=>"edit", :controller=>"per_quizzes", :id=>nil} missing required keys: [:id]
这是在控制器的redirect_to
行上调用的。
任何人都可以看到这里发生了什么导致故障吗?
答案 0 :(得分:0)
我咨询了这些权力,并最终将其改为:
def new
if current_user.per_quiz
redirect_to edit_per_quiz_path(current_user.per_quiz)
flash[:notice] = 'You already took this quiz'
else
@per_quiz = current_user.build_per_quiz
end
end
显然在if
声明之前进行了构建,使测验陷入了一个零但同时不是零的薛定谔猫的情况。