的一些背景。我有有1個測驗和屬於用戶測驗用戶。我想列出用戶所採取的測驗,但我得到一個錯誤。Rails視圖未定義的方法
NoMethodError中的用戶#索引
顯示/Users/Daniel/Documents/cis196/CollegeConnection/app/views/users/index.html.erb其中行#24提出:
未定義的方法`的userName '的零:NilClass 提取的源(圍繞線#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:/用戶/丹尼爾/文檔/ cis196/CollegeConnection
應用程序跟蹤|框架跟蹤|全面跟蹤 應用程序/視圖/用戶/ index.html.erb:24:在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' 應用程序/控制器/ users_controller.rb:25:在'指數」
下面是一些relavent代碼。
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 %>
這是帶有錯誤的視圖。任何幫助將是偉大的!
我仍然得到同樣的錯誤。任何其他想法?哦,並注意,該視圖是一個用戶視圖,而不是一個測驗視圖。 –
錯誤顯示問題發生在'索引'控制器操作,但粘貼的代碼是'創建'操作它看起來像QuizController的創建動作,而不是UserController ...),所以任何改變它的建議(通過在那裏分配值給@user)是不太可能的) – Pavling
我已經更新了我的初始答案。 – Agis