I created an application , which Users can create a Topic and other can post their comments about the topic. I can create a topic now and post.form work but when i post a comment i get
NoMethodError in Posts#create
undefined method `each' for nil:NilClass
Extracted source (around line #2):
1:
2: <% for topic in @topics do %>
3: <li><%=link_to topic.title, topic_path(topic) %></li>
4:
5: <%= will_paginate @topics %>
My posts controller is :
class PostsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
before_filter :correct_user, only: :destroy
def create
@post = current_user.posts.build(params[:post])
if @post.save
flash[:success] = "Konu oluşturuldu!"
redirect_to topic_path(topic)
else
render 'static_pages/home'
end
end
def destroy
@post.destroy
redirect_to root_path
end
private
def correct_user
@post = current_user.posts.find_by_id(params[:id])
redirect_to root_path if @post.nil?
end
end
When i create a post it redirects to localhost/posts … although i want it to stay in that topic . How can i correctly redirect?
I think it is better and a lot more concise to use
@topics.each doinstead offor topic in @topics do.Basically, in your create action, it seems that you aren’t assigning
@topicsany value. So it will be nil. No defined method exists for trying to enumerate over nil, that is why ruby starts looking into the method_missing method of Nil class. Having not found any handling there, the following exception is generated.I’d recommend you to assign some value to
@topics