Reputation: 566
According to the One Month Rails course in the session: Pins Users and Associations
i have to do the following after running rails console
:
Pin.connection #This establishes a connection to the database (And spits out a LOT of unnecessary data)
Pin.inspect #shows all of the parameters for a Pin
CONTROL + D #closes the Console
pin = Pin.first #make sure Pin.first is UPPERCASE
pin.user
But when i write pin.user
i get an error NoMethodError: undefined method 'user' for nil:NilClass
I have added belongs_to :user
and has_many :pins
I dont understand why i am getting that error.
My github is https://github.com/frankzk/pinteresting
Upvotes: 4
Views: 5693
Reputation: 1
If you are like me, all of your code is correct and Mattan has just put a little piece of code in the wrong place.
class PinsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_pin, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
Make sure that before_action :authenticate_user!, except: [:index, :show]
is at the top of the list there.
EDIT: Actually I see you are on an earlier part of the lesson; I'll leave this answer up though because I was directed to this question when trying to figure out the authorization part.
Upvotes: 0
Reputation: 47
Please be sure pins table has the column name user_id. Or check whether the record in the database exists for the first Pin or not.
Upvotes: 0
Reputation: 76774
To clarify, the error is created because the original object (in your case @pin
) is not populated with any data (hence it being nil
).
--
Error
A lot of beginners get confused about this error, but it's quite simple:
@pin.user
^ this calls .user
on the @pin
object. The user
method is created from your rails associations (belongs_to :user
), and is meant to provide you with the associative data.
The problem you have is you're calling .user
on an object which is not populated (it's part of the 'nil'
class), consequently preventing the .user
method from actually running.
--
Fix
To fix this, you should do this:
#app/controllers/pins_controller.rb
Class PinsController < ActieRecord::Base
def show
@pin = Pin.find params[:id] #-> or Pin.first
end
end
#app/views/pins/show.html.erb
<%= @pin.user %>
If you get errors after this, it generally means you either have data inconsistency (no data in your db), or some other part of your system is incoherent.
Upvotes: 3