خرید بک لینک

Vote count: 0

So I'm having people submit a question using a form, then I display all the questions on the same page. It works fine when the validation passes (minimum 25 characters) but when it doesn't pass, I get this error:

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>

I don't really know what's going on. Any ideas?

app/controllers/static_pages_controller:

class StaticPagesController < ApplicationController
  def home
    @questions= Question.all
  end

  def help
  end
end

views/static_pages/home

<div class="row">
    <div class="col-md-12">
        <% @questions.each do |question| %>
        <p> <%= question.content %></p>
        <% end %>
        </div>

</div>

app/controllers/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

models/question.rb

class Question < ActiveRecord::Base
    validates :content, presence: true, length: { minimum: 25}
end

asked 34 secs ago

برچسب: نویسنده: استخدام کار تاريخ: يکشنبه 23 خرداد 1395 ساعت: 15:04

صفحه بندی