undefined local variable or method `user' rails controller issue

18,583

Solution 1

To resolve following error

undefined local variable or method 'user' for #<#<Class:0x00000101b39f28>:0x0000010828c1d0>

In your _version.html.erb partial,

Replace

<h6><%= image_tag user.image_url(:collaborator_thumb).to_s, :class => "profile-pic-thumb" %><%= version.title %>...</h6>

With

<h6><%= image_tag version.user.image_url(:collaborator_thumb).to_s, :class => "profile-pic-thumb" %><%= version.title %>...</h6>

Note version.user.image_url instead of user.image_url. You are getting error because user variable is not defined. BUT version is defined so to access the associated user record you can simply use version.user.

UPDATE

The association with User model is missing in Version model. Set it as below:

class Version < ActiveRecord::Base
  belongs_to :user
  ## ...
end

class User < ActiveRecord::Base
  has_many :versions
  ## ...
end 

UPDATE 2

To store the user_id for a Version instance. Update the new action in your controller as below:

def new 
  @version = @project.versions.build(user_id: @project.user_id) 
end

In the versions new view, add a hidden field for user_id:

<%= f.hidden_field :user_id %>

Update the versions index view as below:

   <ul class="versions">
      <% @project.versions.first(5).each do |version| %>    
        <%= render partial: "version", object: version %>    
      <% end %>
    </ul>

Solution 2

you need to do in _VERSION.HTML.ERB:

<h6><%= image_tag @version.user.image_url(:collaborator_thumb).to_s, :class => "profile-pic-thumb" %><%= version.title %>...</h6>

as you haven't defined user anywhere, by doing this you will be able to access user associated with @version.

You also need to put has_many and belongs_to association in Version and User model.

Share:
18,583
BB500
Author by

BB500

User Interface Developer making the jump into back-end programming

Updated on June 04, 2022

Comments

  • BB500
    BB500 almost 2 years

    Beginner here...I'm trying to display an image but i'm getting the "undefined local variable or method `user'" error message. I think I know whats happening - there is no method but i just can't seem to get it working correctly with what i've tried. I've got a 'projects' model & controller...and a 'versions' model & controller. (pretty sure its just a controller issue so i've posted those files...just let me know if i need to post other files). I believe whats happening is when a user creates a new version the user_id is not being set (at least when I run "version.user_id" for a certain version id, it returns nil). How would i go about...

    1) making sure the user_id is set in the db when the logged in user creates a version? 2) make sure there is a method in the versions index so i can display the profile pic for that user_id to created the version??

    thanks in advance for any help...

    THE ERROR:

    NameError in Versions#index
    Showing /Users/user/Documents/clones/collab/app/views/versions/_version.html.erb where line #3 raised:
    
    undefined local variable or method `user' for #<#<Class:0x00000101b39f28>:0x0000010828c1d0>
    

    THE VERSIONS CONTROLLER:

    class VersionsController < ApplicationController
      before_action :find_project
    
      def new
        @version = Version.new
      end
    
      def show
        @project = Project.find(params[:project_id])
        @version = Version.find(params[:id])
      end
    
      def index
        # @user = User.where(:id => @version.user_id) first figure out how to set user_id on new versions (its nil now)
        @versions = Version.paginate(page: params[:page])
      end
    
      def create
        @project = Project.find(params[:project_id])
        @version = @project.verions.build(version_params)
        if @version.save
          flash[:success] = "You've successfully added a version of this project"
          redirect_to project_path(@project)
        else
          render 'new'
        end
      end
    
      def edit
    
      end
    
      def update
    
      end
    
      def destroy
    
      end
    
      private
    
        def find_project
          @project = Project.find(params[:project_id])
        end
    
        def version_params
          params.require(:version).permit(:title, :project_id, :user_id)
        end
    end
    

    VERSIONS NEW VIEW:

    <% provide(:title, 'New Version') %>
    
    <div class="row-fluid">
      <div class="col-md-5 no-pad">
        <h1>Add a new version to this project</h1>
        <%= bootstrap_form_for @version, :url => project_versions_path do |f| %>
    
          <%= render 'shared/error_messages', object: f.object %>
    
          <%= f.text_field :title %>
    
          <div class="well">
            <h4>Drag and Drop your file here:</h4>
            <%= image_tag("wavicon-large-grey.png", alt: "add file") %>
          </div>
    
          <%= f.button "Create Now! ", class: "btn btn-lg btn-primary" %>
        <% end %>
      </div>
    
    </div>
    

    VERSIONS INDEX VIEW:

    <% provide(:title, @versions ) %>
    
    <div class="row-fluid">
      <section class="no-pad col-md-9">
    
        <%= render :partial => '/projects/project_header' %>
    
        <h4>Version History</h4>
    
        <%= will_paginate %>
    
        <ul class="versions">
          <% @project.versions.first(5).each do |version| %> 
    
            <%= render version %>
    
          <% end %>
        </ul>
    
        <!-- CAN REFACTOR TO BELOW FOR CLEANER CODE
        <ul class="versions">
          <%= render @versions %>
        </ul>
        -->
    
        <%= will_paginate %>
    
      </section>
    </div>
    

    _VERSION.HTML.ERB PARTIAL (linked to in index file above)

    <li>
      <%= link_to project_version_path(@project, version) do %>
        <h6><%= image_tag user.image_url(:collaborator_thumb).to_s, :class => "profile-pic-thumb" %><%= version.title %>...</h6>
        <span class="timestamp pull-right">
          Created <%= time_ago_in_words(version.created_at) %> ago
          <span class="glyphicon glyphicon-time"></span>
        </span>
    
      <% end %>
    </li>
    

    VERSION.RB MODEL (not sure if needed):

    class Version < ActiveRecord::Base
      belongs_to :project
      belongs_to :user
      validates :title, presence: true, length: { maximum: 140 }
    
      default_scope -> { order('created_at DESC') }
    end
    
  • BB500
    BB500 almost 10 years
    Kirti, when I do that I get a similar error...NameError in Versions#index Showing /Users/user/Documents/clones/collab/app/views/versions/_vers‌​ion.html.erb where line #3 raised: undefined method `user' for #<#<Class:0x00000101b39f28>:0x000001057e3690>
  • Saurabh
    Saurabh almost 10 years
    @BB500: You also need to put has_many and belongs_to association in Version and User model.
  • Kirti Thorat
    Kirti Thorat almost 10 years
    I just noticed, you say that you have version.user_id field but you have not set the association in model.
  • BB500
    BB500 almost 10 years
    thanks saurabh - (totally forgot to add that in the models). but now even i get the following error...NoMethodError in Versions#index Showing /Users/user/Documents/clones/collab/app/views/versions/_vers‌​ion.html.erb where line #3 raised: undefined method `user' for nil:NilClass
  • BB500
    BB500 almost 10 years
    it seems like calling version.user is giving a nil value for the user_id. (the versions user is always nil)
  • BB500
    BB500 almost 10 years
    thanks Kirti - now i'm getting the following error...NoMethodError in Versions#index Showing /Users/user/Documents/clones/collab/app/views/versions/_vers‌​ion.html.erb where line #3 raised: undefined method `user' for nil:NilClass. (i've updated my models)
  • BB500
    BB500 almost 10 years
    Hey Kirti - Sorry that chat page keeps timing out on me. But it Worked!!! thanks so much for your help. I will go ahead and award yours as the correct answer...and edit the page to reflect your steps.
  • BB500
    BB500 almost 10 years
    Hey Kirti - i just posted another question related to what you helped me with (it wasn't quite right)...just in case you wanted to take a look. thx stackoverflow.com/questions/23376896/…
  • Afolabi Olaoluwa
    Afolabi Olaoluwa over 4 years
    Hi @KirtiThorat, can you help with this? I think it is my new method/action causing it. stackoverflow.com/questions/58044609/…