我有User has_one Shop
& Shop has_many Branches
。
当我这样做时:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@shop = @user.shop
@branches = @shop.branches
end
...
@user
&@shop
实例变量在视图中有效,但给@branches
了我错误:
undefined method `branches' for nil:NilClass
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:13:in `show'
@branches
但是,如果我在控制器中丢弃:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@shop = @user.shop
end
...
....并在视图中使用它:
@shop.branches
....有用!一直在视图中使用有点累@shop.branches
,所以我更喜欢只使用@branches
.