【问题标题】:Why did I get "undefined method"?为什么我得到“未定义的方法”?
【发布时间】:2011-03-27 04:38:06
【问题描述】:

我有一个配置文件模型,并且一个用户 has_one 配置文件。

这是我的路线:

resources :users
resources :profiles

这是我的控制器中的 show 方法:

def show
  @profile = @user.profile
end

为什么我在尝试访问显示视图时收到此错误:

NoMethodError in ProfilesController#show

undefined method `profile' for nil:NilClass

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 methods


    【解决方案1】:

    您需要初始化@user 实例变量。你可能想做这样的事情:

    def show
      @user = User.find(params[:id])
      @profile = @user.profile
    end
    

    无聊的解释:实例变量(前面有@的)默认为nil。只需为其分配一个非零值即可事实上“实例化”它们。这里,@user 是一个实例变量,它指向 nil,因为它没有被分配任何东西。 profile 是在 nil 的上下文中调用的,它没有 profile 方法,所以你会得到 no method 异常。这与以小写字母开头的局部变量相反,在这种情况下会引发局部变量未找到异常。

    【讨论】:

    • 现在我得到这个错误:ActiveRecord::RecordNotFound in ProfilesController#show Couldn't find User with ID=2
    • ok 那是因为用户不存在,尝试传入一些其他的 id 应该可以工作
    • 这将取决于您的实施。我不知道你的模型是如何构建的。我只是从您对@user 的使用中推断出有一些后端User 具有#profile 方法。
    • @Justin:您提到您以用户身份登录。你是如何“登录”的?您是否使用过诸如 Authlogic 之类的 gem 来处理您的登录?如果您显示您的“登录”代码,我们可以将您指向您要使用的变量(或方法)。
    • 我使用 RESTful 会话登录
    【解决方案2】:

    因为@user 对象是nil?您是否在尝试使用之前填充了 @user 实例变量?

    【讨论】:

      【解决方案3】:

      那是因为@user 是nil,你需要这样的东西

      def show
        @user = User.find(params[:id]) 
        @profile = @user.profile
      end
      

      【讨论】:

        猜你喜欢
        • 2015-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多