我是Rails的新手,正在构建一个quizz应用程序。我在两个模型之间建立了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>
当我点击链接时,我想用与链接中的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的未定义方法"word"(单词是问题的属性)
我想哭。我做错了什么?
附言:我的想法是在"answer"视图中添加一个link_to_unless,它会转到同一级别的下一个问题,除非下一个是零,所以我认为我需要以某种方式用相同的参考键对这些问题进行分组?
它现在可以工作,但我不确定这是否是最漂亮的解决方案。视图/级别/播放为空,因为它只重定向到级别的第一个问题。
class LevelsController < ApplicationController
def startlevel
@levels = Level.all
end
def play
@level = Level.find(params[:id])
@question = Question.find_by_level_id(params[:id])
redirect_to controller: 'questions', action: 'answer', id: @question.id
end
#views/levels/startlevel
<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', :action => "play", :id=>level.id %></td>
</tr>
<% end %>
</table>
问题控制器
class QuestionsController < ApplicationController
def answer
@question= Question.find(params[:id])
end
编辑:路线:
quizz::Application.routes.draw do
resources :questions
resources :levels
get "home/index"
root :to => 'home#index'
match ':controller/:action/:id', via: [:get, :post]
match ':controller/:action/:id.:format', via: [:get, :post]