我是 Rails 新手,我正在构建一个测验应用程序。我在两个模型之间建立了 has_many 和 belongs_to 关联:Level 和 Question。
#models/level.rb
class Level < ActiveRecord::Base
has_many :questions
end
#models/question.rb
class Question < ActiveRecord::Base
belongs_to :level
attr_accessible :level_id
end
我的 LevelController 中有一个动作“startlevel”,它简单地列出了所有级别。
class LevelsController < ApplicationController
def startlevel
@levels = Level.all
end
以及带有链接的视图以转到该级别的第一个问题。我想将关卡的 id 作为参数添加到链接中。我注意到视图 url 中的 1 。我不知道它为什么会出现在那里,以及它是否是我的问题的一部分。
#controller/levels/startlevel/1
<h2>which level would you like to play</h2>
<table>
<tr>
<th>level</th>
</tr>
<% @levels.each do |level| %>
<tr>
<td> level <%=level.number %></td>
<td><%= link_to '<> play this level', :controller => "questions", :action => "answer",:level_id=> level.id%></td>
</tr>
<% end %>
</table>
当我点击链接时,我想使用与 link_to 中的 id 参数匹配的 level_id 转到第一个问题,所以我尝试这样做:
class QuestionsController < ApplicationController
def answer
@question = Question.find_by_level_id(params[:level_id])
end
以这种观点
<p>
<b>Question:</b>
<%=h @question.word %>
</p>
<p>
<b>1:</b>
<%=h @question.ans1 %>
</p>
<p>
<b>2:</b>
<%=h @question.ans2 %>
</p>
<p>
<b>3:</b>
<%=h @question.ans3 %>
</p>
<p>
<b>4:</b>
<%=h @question.ans4 %>
</p>
<%= form_tag(:action => "check", :id => @question.id) do %>
<p>
<b>the correct answer is number: </b>
<%=text_field :ans, params[:ans]%>
</p>
<p><%= submit_tag("check")%></P>
<% end %>
不幸的是,无论我尝试了什么,在过去的几个小时里我得到的只是: nil:NilClass 的未定义方法“单词” (单词是问题的属性)
我想哭。我究竟做错了什么?
ps我的想法是在“答案”视图中添加一个link_to_unless,除非下一个问题为零,否则我认为我需要以某种方式使用相同的参考键对问题进行分组?