[Ruby on Rails] Follow function undefined method ʻid'for nil: NilClass error resolution

スクリーンショット 2020-06-20 06.55.37.png

Premise / What you want to achieve

I want to implement a follow function. ruby 2.5.1p57 Rails 5.2.4.2

The following error message occurred while implementing the follow function.

Problems / error messages that are occurring

error


undefined method `id' for nil:NilClass

Corresponding source code

Table (migration file)

relationships table


class CreateRelationships < ActiveRecord::Migration[5.2]
  def change
    create_table :relationships do |t|
      t.integer :follower_id, foreign_key: true
      t.integer :following_id, foreign_key: true

      t.timestamps null: false
    end

    add_index :relationships, :follower_id
    add_index :relationships, :following_id
    add_index :relationships, [:follower_id, :following_id], unique: true
  end
end

model

relationship.rb


class Relationship < ApplicationRecord
  belongs_to :follower, class_name: "User"
  belongs_to :following, class_name: "User"
  validates :follower_id, presence: true
  validates :following_id, presence: true
end

user.rb


class User < ApplicationRecord
  devise  :database_authenticatable, :registerable,
          :recoverable, :rememberable, :validatable
  has_many :posts, dependent: :destroy
  has_many :likes, dependent: :destroy
  has_many :liked_posts, through: :likes, source: :post
  has_many :comments
  
  def already_liked?(post)
    self.likes.exists?(post_id: post.id)
  end

  has_many :following_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
  has_many :followings, through: :following_relationships, source: :following
  has_many :follower_relationships, class_name: "Relationship", foreign_key: "following_id", dependent: :destroy
  has_many :followers, through: :follower_relationships, source: :follower

  def following?(user)
    following_relationships.find_by(following_id: user.id)
  end

  def follow!(other_user)
    following_relationships.create!(following_id: user.id)
  end

  def unfollow!(other_user)
    following_relationships.find_by(following_id: user.id).destroy
  end
  
end

routing

routes.rb


Rails.application.routes.draw do
  devise_for :users
  root to: "posts#index"

  resources :posts do
    resources :comments, only: :create
    resources :likes, only: [:create, :destroy]
  end

  resources :users do
    member do
      get :following, :followers
    end
  end

  resources :relationships, only: [:create, :destroy]
end

View

ruby:_follow_form.html.haml


- unless current_user?(@user)
  #follow_form
  - if current_user.following?(@user)
    = render 'unfollow'
  - else
    = render 'follow'

controller

users_controller.rb


class UsersController < ApplicationController

  def show
    
  end
  
  def edit
    
  end

  def update
    if current_user.update(user_params)
      redirect_to root_path
    else
      render :edit
    end
  end

  def following
    @user = User.find(id: params[:id])
    binding.pry
    @users = @user.followings
    render 'show_following'
  end

  def followers
    @user = User.find(id: params[:id])
    binding.pry
    @users = @user.followers
    render 'show_follower'
  end

  private

  def user_params
    params.require(:user).permit(:id, :name, :email)
  end

end

What I tried

-It was confirmed that the association of user.rb (user model) was set up correctly. -Checked all over for spelling mistakes in user.rb (user model) and _follow_form.html.haml (partial template).

Meaning of error message

error


following_relationships.find_by(following_id: user.id)

undefined method `id' for nil:NilClass

-I tried to call the id method for nil, but I couldn't find it. ・ User is nil

→ What causes user to become nil? ?? ??

Found error causes and solutions

[email protected] was not defined in the show action of users_controller.rb. The error screen says NoMethodError in Users # show, so I should be suspicious of the show action in users_controller.rb.

I solved it by defining @user as follows in the show action of users_controller.rb.

users_controller.rb


def show
  @user = User.find(params[:id])
end

With params [: id], the value sent with the path is received from the screen before the transition.

Thanks to this article, I was able to resolve the error

I found it on a site called teratail, an engineer's yahoo wisdom bag. [Ruby on Rails] Follow function undefined method ʻid'for nil: NilClass error message appears

Recommended Posts

[Ruby on Rails] Follow function undefined method ʻid'for nil: NilClass error resolution
[Ruby on Rails] undefined method ʻid'for nil: NilClass error resolution method
[Ruby on Rails] NoMethodError undefined method `devise_for'error resolution
Rails error undefined method ʻimage_name'for nil: NilClass handling
[Ruby on Rails] Follow function implementation: Bidirectional
[Ruby on Rails] Search function (model, method selection formula)
[Ruby on Rails] Introduced paging function
[Ruby on Rails] CSV output function
[Ruby on Rails] Comment function implementation
[Ruby on Rails] DM, chat function
[Ruby on Rails] Convenient helper method
[Ruby on Rails] Search function (not selected)
[Rails] Addition of Ruby On Rails comment function
Ruby on Rails installation method [Mac edition]
[Ruby on rails] Implementation of like function
[Ruby on Rails] Logical deletion (withdrawal function)
[Ruby on Rails] NoMethodError: undefined method `t'for # <ActiveRecord :: Migration: 〇〇〇〇> Dealing with errors
Implementation of Ruby on Rails login function (Session)
Rails follow function
Ruby on Rails Email automatic sending function implementation
Ruby on Rails address automatic input implementation method
[Ruby on Rails] Post editing function (update, delete)
[Ruby on Rails] Individual display of error messages
[Ruby on Rails] Asynchronous communication of posting function, ajax
Method summary to update multiple columns [Ruby on Rails]
Implementation of Ruby on Rails login function (devise edition)
[Ruby on Rails] Posting score ranking function (whole display)
[Ruby] Invalid multibyte char (UTF-8) Error resolution method [CSV]
[Ruby on Rails] Post image preview function in refile
Ruby on Rails Refactoring method example summary around MVC
Ruby on Rails Elementary
Ruby on Rails basics
Ruby On Rails Association
Error resolution on Heroku
Ruby on Rails Email automatic sending function setting (using gmail)
[Ruby on Rails] Bookmark (favorite registration, like) function: One direction
Ruby on Rails record search, create if not find_or_create_by method
A note about the seed function of Ruby on Rails
[Ruby on Rails] Implement login function by add_token_to_users with API
When using Slim in Ruby on Rails, "undefined local variable or method` f'for "is displayed in form_with
Ruby on rails learning record -2020.10.03
Portfolio creation Ruby on Rails
Ruby on rails learning record -2020.10.04
[Ruby on Rails] Debug (binding.pry)
Ruby on rails learning record -2020.10.05
Ruby on rails learning record -2020.10.09
Ruby on rails learning record-2020.10.07 ②
Ruby on rails learning record-2020.10.07 ①
Cancel Ruby on Rails migration
[Ruby] Notes on gets method
Ruby on rails learning record -2020.10.06
Ruby on Rails validation summary
Ruby on Rails Basic Memorandum
I want to add a browsing function with ruby on rails
[Ruby on Rails] Posting function that only logged-in users can post
(Ruby on Rails6) Create a function to edit the posted content