简体   繁体   中英

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 %>

You grab the @user in your show, but then you use current_user.posts to set the @posts . That should probably be @user.posts

Alright, after doing a little rake db:migrate & restarting the server, everything seems to work. Didn't change anything.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM