2016-06-12 90 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

相關問題