I have a profile model, and a user has_one profile.
Here’s my route:
resources :users
resources :profiles
Here’s the show method in my controller:
def show
@profile = @user.profile
end
Why do I get this error when I try to access the show view:
NoMethodError in ProfilesController#show
undefined method `profile' for nil:NilClass
You need to initialize the
@userinstance variable. You probably want to do something like this:Boring explanation: Instance variables (the ones with
@in the front) arenilby default. They can be de facto “instantiated” by just assigning a non-nil value to it. Here,@useris an instance variable, and it points to nil because it hasn’t been assigned anything.profileis invoked in the context ofnil, which doesn’t have aprofilemethod, so you get the no method exception. This is as opposed to local variables, starting with a lower-cased letter, which would in this case have raised a local variable not found exception.