[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

-@User 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
[Ruby on Rails] undefined method ʻid'for nil: NilClass error resolution method
Spring Boot + PostgreSQL error resolution method
[Ruby on Rails] Follow function undefined method ʻid'for nil: NilClass error resolution
RSpec error resolution undefined method `feature'for RSpec: Module
[Ruby on Rails] NoMethodError undefined method `devise_for'error resolution
[Ruby on Rails] Follow function implementation: Bidirectional
rspec Error: ActionView :: Template :: Error: undefined method `name'for nil: NilClass
[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
RSpec error resolution undefined method `feature'for RSpec: Module
[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
Validation settings for Ruby on Rails login function
Implementation of Ruby on Rails login function (Session)
[Ruby on Rails] How to display error messages
Rails follow function
Ruby on Rails Email automatic sending function implementation
Ruby on Rails address automatic input implementation method
[Ruby on Rails] How to use session method
[Ruby on Rails] Post editing function (update, delete)
[Ruby on Rails] Individual display of error messages
Ruby on Rails Incorrect string value error resolution when posting a form in Japanese
About the relationship between Rails credentials.yml.enc and master.key (undefined method `[]'for nil: NilClass (NoMethodError))
Ruby on Rails <2021> Implementation of simple login function (form_with)
[Ruby on Rails] Asynchronous communication of posting function, ajax
Method summary to update multiple columns [Ruby on Rails]
[Ruby on Rails Tutorial] Error in the test in Chapter 3
Implementation of Ruby on Rails login function (devise edition)
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)
From Ruby on Rails error message display to Japanese localization
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
Implement follow function in Rails
Ruby on rails learning record -2020.10.09
Ruby on Rails config configuration
Ruby on Rails basic learning ①
[Ruby on Rails] about has_secure_password
Ruby on rails learning record-2020.10.07 ②
Commentary on partial! --Ruby on Rails
[Rails] (Supplement) Implemented follow function
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 for beginners! !! Post list / detailed display function summary
[Ruby on Rails] Posting function that only logged-in users can post