所以我讓人們使用表單提交問題,然後在同一頁面上顯示所有問題。保存到數據庫失敗時沒有方法錯誤
NoMethodError in Questions#create
Showing /home/ubuntu/workspace/app/views/static_pages/home.html.erb where line #20 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #20):
<div class="row">
<div class="col-md-12">
<% @questions.each do |question| %> <--- this is line 20
<p> <%= question.content %></p>
<% end %>
</div>
我真的不知道發生了什麼事情:當驗證通過(最少25個字符),但是當它不通過,我得到這個錯誤,它工作正常。有任何想法嗎?
應用程序/控制器/ static_pages_controller:
class StaticPagesController < ApplicationController
def home
@questions= Question.all
end
def help
end
end
的意見/ static_pages /家
<div class="row">
<div class="col-md-12">
<% @questions.each do |question| %>
<p> <%= question.content %></p>
<% end %>
</div>
</div>
應用程序/控制器/ questions_controller:
class QuestionsController < ApplicationController
#before_action :logged_in_user, only: [:create]
def create
@question = Question.new(question_params) #this might not work
if @question.save
flash[:success] = "Question added"
redirect_to root_path
else
flash[:danger] = "Add question failed. Try making the question longer."
render 'static_pages/home'
end
end
private
def question_params
params.require(:question).permit(:content)
end
end
型號/ question.rb
class Question < ActiveRecord::Base
validates :content, presence: true, length: { minimum: 25}
end
您的問題表中是否有任何記錄? – Pavan