Search code examples
ruby-on-railsdeviseposts

I'm getting an undefined method `each' for nil:NilClass | Trying to add posts to users profiles


I'm struggling with my rails app since I'm trying to add the posts from the users on their profile page. I'm using device and I've looked online for a solution, but none seems to be working.

I'm running a Rails server 5.2.

Here are a few bits of my code :

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :posts
end

#app/models/post.rb
class Post < ActiveRecord::Base
   belongs_to :user
end

This is the users.controller.rb

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])

    @posts = current_user.posts
  end

end

and my posts_controller.rb :

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:show, :index]
  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end

This is the users/show.html.erb

<%= @user.about %>

  <% @posts.each do |post| %>
    <%= post.title %>
<% end %>

It's seems not to work since I'm having this specific error : undefined method `each' for nil:NilClass

<%= @user.about %>

  <% @posts.each do |post| %>
    <%= post.title %>
<% end %>


Solution

  • Since you find the solution, here is the suggestion instead.

    class UsersController < ApplicationController
      def show
        @user = User.find(params[:id])
    
        @posts = current_user.posts
      end
    end
    

    Change it to

    class UsersController < ApplicationController
      before_action :authenticate_user!
    
      def show
        @user = current_user
        @posts = current_user.posts
      end
    end
    
    • Added before_action :authenticate_user! in order to get current user, in most case user need to log in in order to view/edit their profile, therefore we should require user to log-in
    • Changed to @user = current_user because now logged-in user is the user object that we need to show or edit