我的测验模型和我的quiz_session模型之间有一对一关联,当我尝试在测验控制器中访问@ quiz.quiz_session时,quiz_session对象为零。 但是当我在rails控制台中检查我的quiz_session对象时,它会显示一个引用的测验。
# quizzes_controller.rb:
def show
@quiz_session = @quiz.quiz_session
logger.debug "quizzes_controller"
logger.debug @quiz_session.inspect
end
#development.log output:
quizzes_controller
nil
#quiz.rb:
class Quiz < ApplicationRecord
belongs_to :quiz_session, dependent: :destroy
accepts_nested_attributes_for :quiz_session, reject_if: :all_blank, allow_destroy: true
end
#quiz_session.rb:
class QuizSession < ApplicationRecord
has_one :quiz
end
#rails console:
irb(main):001:0> QuizSession.first
QuizSession Load (0.0ms) SELECT "quiz_sessions".* FROM "quiz_sessions" ORDER BY "quiz_sessions"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<QuizSession id: 31, access_key: "srtjki356xm", created_at: "2017-04-23 22:54:51", updated_at: "2017-04-23 22:54:51", quiz_id: 1, current_question_index: nil>
irb(main):002:0> Quiz.find(1)
Quiz Load (0.0ms) SELECT "quizzes".* FROM "quizzes" WHERE "quizzes"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<Quiz id: 1, title: "Chapter 1.1", lecture_unit: "2017-03-19", unlocked_at: "2017-03-19 14:00:00", course_id: 1, created_at: "2017-03-19 02:27:28", updated_at: "2017-03-19 02:27:28">
我是Ruby on Rails的新手并使用Rails 5.0.2。任何帮助将不胜感激:)
答案 0 :(得分:0)
尝试以下方法:
# quizzes_controller.rb:
def show
@quiz_session = @quiz.quiz_session
logger.debug "quizzes_controller"
logger.debug @quiz_session.inspect
end
#quiz.rb:
class Quiz < ApplicationRecord
has_one :quiz_session, dependent: :destroy
accepts_nested_attributes_for :quiz_session, reject_if: :all_blank, allow_destroy: true
end
#quiz_session.rb:
class QuizSession < ApplicationRecord
belongs_to :quiz
end
这是因为你的quiz_session包含quiz_id = 1.但这不是硬编码事情的好方法。您应该使逻辑从请求和传递中传递测验ID。然后动态制作@quiz = Quiz.find(params[:quiz_id])
。目前,您可以使用上述解决方案。