0

I am not sure that it is even related but since i added devise i am getting a no method error which reads as follows. undefined method `posts' for nil:NilClass This is specifically directed at the following line of code.

@post = current_user.posts.build

I am rather stuck here as i have checked all the obvious and unless i remove the code so it reads

@post = Post.new

I am otherwise unable to add new posts. I have added the full code below. Posts Controller

class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]

def index
    @posts = Post.all.order("created_at DESC")
end

def show
end

def new
    @post = current_user.posts.build
end

def create
    @post = current_user.posts.build(post_params)

    if @post.save
        redirect_to @post
    else
        render 'new'
    end
end

def edit
end

def update
    if @post.update(post_params)
        redirect_to @post
    else
        render 'edit'
    end
end

def destroy
    @post.destroy
    redirect_to root_path
end

private

def find_post
    @post = Post.find(params[:id])
end

def post_params
    params.require(:post).permit(:title, :content)
end
end

Post model`

 class Post < ActiveRecord::Base
    belongs_to :user
 end

User model

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :posts
end

new html haml

%h1 New Post

= render 'form'
2
  • 1
    There's no user logged in, so current_user is nil. Commented Jan 19, 2015 at 13:20
  • Apparently there is no logged in user. Are you logged in? Is the CSRF token set correctly? Commented Jan 19, 2015 at 13:21

2 Answers 2

4

The code looks ok...

But what happens if there is no user signed in? try add

before_action :authenticate_user!

or ask

user_signed_in?

before you try to access the logged in user.

Sign up to request clarification or add additional context in comments.

1 Comment

@Emma Always read the documentation, before using the ruby gems, it will make your work easier and you will not face such difficulties.
0

Need to see your how you have integrated your devise. But yes, maybe your not signed in that's why the nil error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.