2012-05-18 24 views
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

回答

2

該消息表明@shop在控制器中爲零。如果在視圖中有相同的請求,則意味着@shop已經在控制器之後的其他地方設置。

+0

謝謝!我已經爲@ @ branches添加了'除非@ shop.nil?',現在它可以工作! –

相關問題