所以我让人们使用表单提交问题,然后在同一页面上显示所有问题。保存到数据库失败时没有方法错误
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