为什么我的rails关联在控制器中不起作用但它们在视图中工作?

时间:2012-05-18 17:39:33

标签: ruby-on-rails associations instance-variables

我有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&amp; @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

1 个答案:

答案 0 :(得分:2)

该消息表明控制器中@shop为零。如果它在视图中使用相同的请求,则意味着在控制器之后的其他地方肯定设置了@shop

相关问题