2016-06-12 96 views
0

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

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 
+0

您的问题表中是否有任何记录? – Pavan

回答

0

It works fine when the validation passes (minimum 25 characters) but when it doesn't pass, I get this error undefined method `each' for nil:NilClass

这是因为的Rails无法找到@questions验证失败,因为你没有把它在这种情况下。添加它应该让你去。

def create 
    @question = Question.new(question_params) 
    if @question.save 
    flash[:success] = "Question added" 
    redirect_to root_path 
    else 
    flash[:danger] = "Add question failed. Try making the question longer." 
    @questions = Question.all #All you need is to add this line 
    render 'static_pages/home' 
    end 
end 
+0

@nachime关键在于'render'static_pages/home''。 'render'只是加载页面。它没有进入动作,所以''问题'在'home'方法被视为无。 – Pavan

相关问题