9 Replies - 1706 Views - Last Post: 07 February 2018 - 11:52 AM Rate Topic: -----

#1 brandonm222   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 18-October 14

Undefined method `each_with_index' for nil:NilClass

Posted 01 February 2018 - 11:56 PM

Hi there,

I am kind of new at this. I am trying to merge two apps together and add messeging to my program. However, after following both tutorials I am stuck. And get this error: undefined method `each_with_index' for nil:NilClass on here:

Code:
</div>
  <div class="col-lg-3">
    <%= render 'shared/links' %>
  </div>
<% @users.each_with_index do |index| %>
    <tr>
      <td><%= index +=1 %></td>
      <td><%= user.name %></td>
      <td>
        <%= link_to "Send Message", "#", class: "btn btn-success btn-xs start-conversation",

Again I am new to ruby on rails so I don't know exactly what data and code you need to know what my error would be.

I am using Rails 5 and Ruby 2.5.0

Here are the two tutorials:

http://josephndungu....n-ruby-on-rails

https://github.com/scaffeinate/socify

The social media part works no problem but the chat part doesn't

Is This A Good Question/Topic? 0
  • +

Replies To: Undefined method `each_with_index' for nil:NilClass

#2 ndc85430   User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 979
  • View blog
  • Posts: 3,858
  • Joined: 13-June 14

Re: Undefined method `each_with_index' for nil:NilClass

Posted 02 February 2018 - 01:09 AM

It seems pretty self explanatory: users is nil rather than a sequence (list, array, or whatever else Ruby calls it) containing some users. Where does users come from? How is it being defined? You need to start there and work out why it is nil.

Presumably you're just new to Rails and not to Ruby. If not, you should really go back and learn the language before trying to dive in to a web framework.
Was This Post Helpful? 0
  • +
  • -

#3 NeoTifa   User is offline

  • NeoTifa Codebreaker, the Scourge of Devtester
  • member icon





Reputation: 4550
  • View blog
  • Posts: 19,192
  • Joined: 24-September 08

Re: Undefined method `each_with_index' for nil:NilClass

Posted 02 February 2018 - 09:05 AM

Make sure your routes.rb has the resources for user and the controller should dictate where the @users is coming from, something to this effect:

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


((^example))

Since I can't see anything else, try making sure of this.
Was This Post Helpful? 0
  • +
  • -

#4 brandonm222   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 18-October 14

Re: Undefined method `each_with_index' for nil:NilClass

Posted 02 February 2018 - 05:14 PM

This is my actual program. I hope this helps in making things clearer.
I am hoping I am allowed to add links to this forum. It is on One drive.
My link
Was This Post Helpful? 0
  • +
  • -

#5 NeoTifa   User is offline

  • NeoTifa Codebreaker, the Scourge of Devtester
  • member icon





Reputation: 4550
  • View blog
  • Posts: 19,192
  • Joined: 24-September 08

Re: Undefined method `each_with_index' for nil:NilClass

Posted 03 February 2018 - 10:45 AM

For security reasons, I'm not opening that. Could you just post the relevant code? Also, this sounds stupid, but did you actually make the database tables? Did you migrate them?
Was This Post Helpful? 1
  • +
  • -

#6 brandonm222   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 18-October 14

Re: Undefined method `each_with_index' for nil:NilClass

Posted 05 February 2018 - 08:22 PM

Sorry for the delay in my reply. Here is my code:

This is my friends.html.erb
<div class="row">
  <div class="col-lg-3">
    <%= render 'shared/user_info' %>
  </div>
  <div class="col-lg-6 well">
    <h3>Friends</h3>
    <hr>
    <div id="friends">
      <%= render(@friends) || render('shared/no_resource', resources: 'Friends') %>
    </div>
    <%= render 'shared/paginate', resources: @friends %>
  </div>
  <div class="col-lg-3">
    <%= render 'shared/links' %>
  </div>

<% @users.each_with_index do |user, index| %>
    <tr>
      <td><%= index +=1 %></td>
      <td><%= user.name %></td>
      <td>
        <%= link_to "Send Message", "#", class: "btn btn-success btn-xs start-conversation",
                    "data-sid" => current_user.id, "data-rip" => user.id %>
      </td>
    </tr>
<% end %>
  
</div>


This is my User Controller
# Copyright (c) 2015, @sudharti(Sudharsanan Muralidharan)
# Socify is an Open source Social network written in Ruby on Rails This file is licensed
# under GNU GPL v2 or later. See the LICENSE.

class UsersController < ApplicationController
  before_action :authenticate_user!
  before_action :set_user
  before_action :check_ownership, only: [:edit, :update]
  respond_to :html, :js

  def index
      @users = User.where.not("id = ?",current_user.id).order("created_at DESC")
      @conversations = Conversation.involving(current_user).order("created_at DESC")
  end
  def show
    @activities = PublicActivity::Activity.where(owner: @user).order(created_at: :desc).paginate(page: params[:page], per_page: 10)
  end

  def edit
  end

  def update
    if @user.update(user_params)
      redirect_to user_path(@user)
    else
      render :edit
    end
  end

  def deactivate
  end

  def friends
    @friends = @user.following_users.paginate(page: params[:page])
  end

  def followers
    @followers = @user.user_followers.paginate(page: params[:page])
  end

  def mentionable
    render json: @user.following_users.as_json(only: [:id, :name]), root: false
  end

  private

  def user_params
    params.require(:user).permit(:name, :about, :avatar, :cover,
                                 :sex, :dob, :location, :phone_number)
  end

  def check_ownership
    redirect_to current_user, notice: 'Not Authorized' unless @user == current_user
  end

  def set_user
    @user = User.friendly.find_by(slug: params[:id]) || User.find_by(id: params[:id])
    render_404 and return unless @user
  end
end



This is my routes:

Rails.application.routes.draw do

  resources :posts
  resources :comments, only: [:create, :destroy]
  devise_for :users
  resources :users do
    member do
      get :friends
      get :followers
      get :deactivate
      get :mentionable
    end
  end

  resources :events do
    collection do
      get :calendar
    end
  end

  authenticated :user do
    root to: 'home#index', as: 'home'
  end
  unauthenticated :user do
    root 'home#front'
  end

  resources :conversations do
    resources :messages
  end

  match :follow, to: 'follows#create', as: :follow, via: :post
  match :unfollow, to: 'follows#destroy', as: :unfollow, via: :post
  match :like, to: 'likes#create', as: :like, via: :post
  match :unlike, to: 'likes#destroy', as: :unlike, via: :post
  match :find_friends, to: 'home#find_friends', as: :find_friends, via: :get
  match :about, to: 'home#about', as: :about, via: :get

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end



Is there anything else you need to figure out what is going on?
Was This Post Helpful? 0
  • +
  • -

#7 NeoTifa   User is offline

  • NeoTifa Codebreaker, the Scourge of Devtester
  • member icon





Reputation: 4550
  • View blog
  • Posts: 19,192
  • Joined: 24-September 08

Re: Undefined method `each_with_index' for nil:NilClass

Posted 06 February 2018 - 10:58 AM

Could I also get the whole stack trace?
Was This Post Helpful? 0
  • +
  • -

#8 brandonm222   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 18-October 14

Re: Undefined method `each_with_index' for nil:NilClass

Posted 06 February 2018 - 03:23 PM

View PostNeoTifa, on 06 February 2018 - 10:58 AM, said:

Could I also get the whole stack trace?


I hope this is what you are refering to:

Started GET "/users/brandon-m/friends" for ::1 at 2018-02-06 14:22:20 -0800
Processing by UsersController#friends as HTML
  Parameters: {"id"=>"brandon-m"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."slug" = ? LIMIT ?  [["slug", "brandon-m"], ["LIMIT", 1]]
  Rendering users/friends.html.erb within layouts/application
  Rendered shared/_avatar.html.erb (64.3ms)
  Merit::Sash Load (0.2ms)  SELECT  "sashes".* FROM "sashes" WHERE "sashes"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  Merit::Score Load (0.1ms)  SELECT "merit_scores".* FROM "merit_scores" WHERE "merit_scores"."sash_id" = ?  [["sash_id", 1]]
   (0.1ms)  SELECT SUM("merit_score_points"."num_points") AS sum_num_points, "merit_score_points"."score_id" AS merit_score_points_score_id FROM "merit_score_points" WHERE "merit_score_points"."score_id" = ? GROUP BY "merit_score_points"."score_id"  [["score_id", 1]]
  Merit::BadgesSash Load (0.1ms)  SELECT "badges_sashes".* FROM "badges_sashes" WHERE "badges_sashes"."sash_id" = ?  [["sash_id", 1]]
  Rendered shared/_user_info.html.erb (145.7ms)
  User Load (0.2ms)  SELECT  "users".* FROM "users" INNER JOIN "follows" ON "follows"."followable_id" = "users"."id" AND "follows"."followable_type" = ? WHERE "follows"."blocked" = ? AND "follows"."follower_id" = ? AND "follows"."follower_type" = ? AND "follows"."followable_type" = ? LIMIT ? OFFSET ?  [["followable_type", "User"], ["blocked", false], ["follower_id", 1], ["follower_type", "User"], ["followable_type", "User"], ["LIMIT", 10], ["OFFSET", 0]]
  Rendered shared/_avatar.html.erb (0.6ms)
  Follow Load (0.6ms)  SELECT  "follows".* FROM "follows" WHERE "follows"."followable_id" = ? AND "follows"."followable_type" = ? AND "follows"."blocked" = ? AND "follows"."follower_id" = ? AND "follows"."follower_type" = ? ORDER BY "follows"."id" ASC LIMIT ?  [["followable_id", 2], ["followable_type", "User"], ["blocked", false], ["follower_id", 1], ["follower_type", "User"], ["LIMIT", 1]]
  Rendered follows/_form.html.erb (12.3ms)
  Rendered collection of users/_user.html.erb [1 times] (16.6ms)
  Rendered shared/_paginate.html.erb (1.4ms)
  Rendered shared/_links.html.erb (1.8ms)
  Rendered users/friends.html.erb within layouts/application (180.4ms)
Completed 401 Unauthorized in 202ms (ActiveRecord: 3.7ms)



NoMethodError - undefined method `each_with_index' for nil:NilClass:
  app/views/users/friends.html.erb:17:in `_app_views_users_friends_html_erb__4179028047266865181_70225343412200'

Started POST "/__better_errors/ca6db73ccb69854b/variables" for ::1 at 2018-02-06 14:22:21 -0800



Was This Post Helpful? 0
  • +
  • -

#9 sepp2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2745
  • View blog
  • Posts: 4,405
  • Joined: 21-June 11

Re: Undefined method `each_with_index' for nil:NilClass

Posted 07 February 2018 - 07:12 AM

View Postbrandonm222, on 06 February 2018 - 11:23 PM, said:

  app/views/users/friends.html.erb:17:in `_app_views_users_friends_html_erb__4179028047266865181_70225343412200'



Okay, so the error happens on line 17 of friends.html.erb, which is:

<% @users.each_with_index do |user, index| %>


So @users is nil. So let's look at where @users should be set and find out why it isn't. Since we're in the friends-view, the needed variables should be set in the friends action of the controller, so let's look at that:

def friends
  @friends = @user.following_users.paginate(page: params[:page])
end


So mystery solved, friends simply does not set a variable named @users (nor do any of the before_actions).
Was This Post Helpful? 1
  • +
  • -

#10 brandonm222   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 18-October 14

Re: Undefined method `each_with_index' for nil:NilClass

Posted 07 February 2018 - 11:52 AM

View Postsepp2k, on 07 February 2018 - 07:12 AM, said:

View Postbrandonm222, on 06 February 2018 - 11:23 PM, said:

  app/views/users/friends.html.erb:17:in `_app_views_users_friends_html_erb__4179028047266865181_70225343412200'



Okay, so the error happens on line 17 of friends.html.erb, which is:

<% @users.each_with_index do |user, index| %>


So @users is nil. So let's look at where @users should be set and find out why it isn't. Since we're in the friends-view, the needed variables should be set in the friends action of the controller, so let's look at that:

def friends
  @friends = @user.following_users.paginate(page: params[:page])
end


So mystery solved, friends simply does not set a variable named @users (nor do any of the before_actions).



Wow honestly I appreciate it! That worked I can't believe it was that simple! Thanks a lot!!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1