I’ve got User has_one Shop & Shop has_many Branches.
When I do this:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@shop = @user.shop
@branches = @shop.branches
end
...
The @user & @shop instance variable works in view, but @branches gives me the error:
undefined method `branches' for nil:NilClass
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:13:in `show'
However, if I discard @branches in the controller:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@shop = @user.shop
end
...
….and use this in the view:
@shop.branches
….it works! It’s kinda tiring to use @shop.branches in the view all the time, so I prefer to just use @branches.
The message indicates that
@shopis nil in the controller. If with the same request it works in the view, it means that certainly@shophas been set somewhere else after the controller.