0
我有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
。
謝謝!我已經爲@ @ branches添加了'除非@ shop.nil?',現在它可以工作! –