我的应用程序的一点背景。我的用户有 1 个测验和一个属于用户的测验。我正在尝试列出用户参加的测验,但出现错误。
用户中的 NoMethodError#index
显示 /Users/Daniel/Documents/cis196/CollegeConnection/app/views/users/index.html.erb 其中第 24 行提出:
nil:NilClass 的未定义方法 `userName' 提取的源代码(第 24 行附近):
<% @user.each do |u| %>
<tr>
<td><h6><%= u.quiz.userName%></h6></td>
<td><h6><%= u.quiz.q1 %></h6></td>
<td><% for q in u.quiz.q2 %>
<% if q != nil %>
Rails.root:/Users/Daniel/Documents/cis196/CollegeConnection
应用程序跟踪 | 框架跟踪 | 完整跟踪 app/views/users/index.html.erb:24:in block in _app_views_users_index_html_erb__3921348574137420689_70261694365660'
app/views/users/index.html.erb:22:in
_app_views_users_index_html_erb__3921348574137420689_70261694365660' app/controllers/users_controller.rb:25:in `index'
这是一些相关的代码。
class User < ActiveRecord::Base
has_one :quiz, :class_name => 'Quiz'
attr_accessible :name, :email, :password, :password_confirmation, :position, :remember_me
validates :name, :presence => true
validates_length_of :name, :maximum=>30
validates :name, :format => { :with => /\A[a-zA-Z]+\z/,
:message => "Only letters allowed" }
validates_presence_of :position
validates :email, :presence => true
validates :email, :uniqueness => true
scope :college, where(position: 'College')
scope :highschool, where(position: 'High School')
end
class Quiz < ActiveRecord::Base
belongs_to :user
validates :q1, :presence => true
validates :q2, :presence => true
validates :q3, :presence => true
serialize :q2
has_many :activities
end
def create
@quiz = current_user.quizzes.build(params[:quiz])
# @quiz = Quiz.new(params[:quiz])
@quiz.userName=current_user.name
@activities = Activity.all
respond_to do |format|
if @quiz.save
format.html { redirect_to @quiz, notice: 'Thank You for Taking the Quiz!.' }
format.json { render json: @quiz, status: :created, location: @quiz }
else
format.html { render action: "new" }
format.json { render json: @quiz.errors, status: :unprocessable_entity }
end
end
end
<% @user.each do |u| %>
<tr>
<td><h6><%= u.quiz.userName%></h6></td>
<td><h6><%= u.quiz.q1 %></h6></td>
<td><% for q in u.quiz.q2 %>
<% if q != nil %>
<h6><%= q %></h6>
<% end %>
<% end %>
<td><h6><%= u.quiz.q3 %></h6></td>
<td>X</td>
</tr>
<% end %>
这是有错误的视图。任何帮助都会很棒!